﻿using BLL.Base;
using CommandService;
using Entity;
using Entity.DbEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SysFrameWork;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL.ERPAPI;
using BLL.sys;
using BLL.Base;
using PubMethod = BLL.Base.PubMethod;
using BLL.custom;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using QRCoder;
using System.Drawing;
using System.Drawing.Imaging;
using GL_CommonPrint.DataModels;
using GL_CommonPrint;
using Entity.ViewEntity;

namespace BLL.Plan
{
    public class PlanPaiChanBLL : SysFrameWork.PubMethod
    {
        Commands cmd;
        SysFrameWork.LoginInfo userLogin;
        Tools.TxtLogHelper txt;
        ReturnResult rsl;
        List<OperateModel> operList;
        OperateModel oper;
        DingHelper ding;
        PubMethod pub;
        public PlanPaiChanBLL()
        {
            cmd = new Commands();
            userLogin = new SysFrameWork.LoginInfo();
            txt = new Tools.TxtLogHelper();
            ding = new DingHelper();
            pub = new PubMethod();
        }

        //获取管理员角色编码
        public string getMaxRole()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select * from sys_powerConfig_groups where groupName = '管理员角色'");
            var roleTable = cmd.GetDataTable(sb.ToString());//获取管理员角色
            var maxR = "undefined";
            if (roleTable.Rows.Count > 0)
            {
                maxR = roleTable.Rows[0]["groupCode"].ToString();
            }
            return maxR;
        }


        /// <summary>
        /// 计划排产列表
        /// </summary>
        /// <param name="condition">检索条件</param>
        /// <returns></returns>
        public ReturnResult PaiChanList(string pageIndex, string pageSize, ref string pageCount, string condition,string canshu1=null)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
                var maxR = getMaxRole();
                #region
                sb.Append(" isdel=0 ");
                if (string.IsNullOrWhiteSpace(canshu1))
                {
                    sb.Append(" and plType!='P-ZhiZao' ");//生产计划的派工单列表
                    if (userLogin.UserInfo().isAdmin == 0 && !userLogin.UserInfo().powerRole.Equals(maxR))
                    {
                        sb.Append(" and ( createuser='" + userLogin.UserInfo().userCode + "'  or groupCode in ");
                        sb.Append(" (select groupCode from V_productionSet_userGroup where userCode='" + userLogin.UserInfo().userCode + "')) ");
                    }
                }
                else
                {
                    sb.Append(" and plType='P-ZhiZao' ");//织造计划的派工单列表
                }
                
                string orderSql = "id desc";
                if (!string.IsNullOrWhiteSpace(canshu1))
                {
                    orderSql = "sDate,orderNum,createtime desc";
                }
                foreach (JProperty obj in json.Properties())
                {
                    if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                    {
                        if (obj.Name == "parentCode")
                        {
                            if (!string.IsNullOrWhiteSpace(json["gxCode"].ToString()))
                            {
                                continue;
                            }
                        }
                        if (obj.Name == "isFinish")
                        {
                            continue;
                        }
                        if (!string.IsNullOrWhiteSpace(sb.ToString()))
                        {
                            sb.Append(" and ");
                        }
                        if (obj.Name == "cStatus")
                        {
                            var sArr = obj.Value.ToString().Split(',');
                            string isFinish = "";
                            foreach (string s in sArr)
                            {
                                if (!string.IsNullOrWhiteSpace(s))
                                {
                                    isFinish += "'" + s + "',";
                                }
                            }
                            sb.Append("isFinish in (" + isFinish.TrimEnd(',') + ")");
                        }
                        else
                        {
                            sb.Append(obj.Name + " like '%" + obj.Value + "%' ");
                        }

                    }
                }
                #endregion
                var list = cmd.PageList("V_PlanPaiChan_info", pageIndex, pageSize, sb.ToString(), orderSql, ref pageCount);
                this.FinishTotal(ref list);
                this.planIsTuiLiao(ref list);

                //canbg:派工单能不能报工   
                //canBG:派工单是否显示报工按钮(登录人所在班组和派工班组一致就可以)

                if (userLogin.UserInfo().isAdmin == 0 && string.IsNullOrWhiteSpace(canshu1))
                {
                    this.BZCompare(ref list);   //生产计划，非管理员，只班组人员显示报工按钮
                }
                else
                {
                    //织造计划目前能看派工的机台进行到哪个派工单了，哪个就能显示报工按钮
                    List<string> maList = new List<string>();
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (!maList.Contains(list[i]["maCode"].ToString()))
                        {
                            list[i]["canBG"] = "1";
                            maList.Add(list[i]["maCode"].ToString());
                        }
                        else
                        {
                            list[i]["canBG"] = "0";
                        }
                    }
                }

                if (list != null && list.Count > 0)
                {
                    rsl.Result = true;
                    rsl.Data = list;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        //派工单是否显示报工按钮(登录人所在班组和派工班组一致就可以)
        private void BZCompare(ref List<Dictionary<string, string>> list)
        {
            StringBuilder sb = new StringBuilder();
            #region
            sb.Append("select * from fun_Users_gangwei where isdel=0 and userCode='" + userLogin.UserInfo().userCode + "'");
            var bzTable = cmd.GetDataTable(sb.ToString());
            if (bzTable.Rows.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    var find = false;
                    foreach (DataRow dr in bzTable.Rows)
                    {
                        if (list[i]["groupCode"].ToString().Equals(dr["groupCode"].ToString()))
                        {
                            find = true;
                            continue;
                        }
                    }
                    if (find)
                        list[i]["canBG"] = "1";
                    else
                        list[i]["canBG"] = "0";
                }
            }
            #endregion
        }

        /// <summary>
        /// 派工完成情况统计方法
        /// </summary>
        /// <param name="list"></param>
        public void FinishTotal(ref List<Dictionary<string, string>> list)
        {
            StringBuilder sb = new StringBuilder();
            #region
            for (int i = 0; i < list.Count; i++)
            {
                sb.Clear();
                sb.Append("select sum(CONVERT(decimal(18,1),yNum)) yNum,sum(CONVERT(decimal(18,1),nNum)) nNum ");
                sb.Append("from pi_PlanBaogong_main where isdel=0 and pKey='" + list[i]["pKey"] + "'");
                var table = cmd.GetDataTable(sb.ToString());

                for (int x = 0; x < table.Rows.Count; x++)
                {
                    list[i]["fNum"] = table.Rows[0]["yNum"].ToString();
                    list[i]["nNum"] = table.Rows[0]["nNum"].ToString();
                }
                if (string.IsNullOrWhiteSpace(list[i]["fNum"].ToString()))
                    list[i]["fNum"] = "0";
                if (string.IsNullOrWhiteSpace(list[i]["nNum"].ToString()))
                    list[i]["nNum"] = "0";
            }
            #endregion
        }

        /// <summary>
        /// 计划退料情况
        /// </summary>
        /// <param name="list"></param>
        private void planIsTuiLiao(ref List<Dictionary<string, string>> list)
        {
            StringBuilder sb = new StringBuilder();
            #region
            for (int i = 0; i < list.Count; i++)
            {
                sb.Clear();
                sb.Append("select * from pi_PaiGong_material_main where status = 'bl-in' and plCode like '%");
                sb.Append(list[i]["ppId"] + "'");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                    list[i]["isTuiLiao"] = "1";
                else
                    list[i]["isTuiLiao"] = "0";
            }
            #endregion
        }

        /// <summary>
        /// 派工信息更新方法
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult UpdatePaiGong(string datas)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                if (string.IsNullOrWhiteSpace(datas))
                {
                    rsl.Message = "提交数据为空";
                    return rsl;
                }
                operList = new List<OperateModel>();
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                DbPlanPaiGongMain paiGong = JsonConvert.DeserializeObject<DbPlanPaiGongMain>(datas);
                if (string.IsNullOrWhiteSpace(paiGong.groupCode))
                {
                    rsl.Message = "生产班组不允许为空";
                    return rsl;
                }
                if (string.IsNullOrWhiteSpace(paiGong.number))
                {
                    rsl.Message = "派工数量不允许为空";
                    return rsl;
                }
                if (string.IsNullOrWhiteSpace(paiGong.gxCode))
                {
                    rsl.Message = "工序不允许为空";
                    return rsl;
                }
                if (string.IsNullOrWhiteSpace(paiGong.sDate))
                {
                    rsl.Message = "生产日期不允许为空";
                    return rsl;
                }
                if (string.IsNullOrWhiteSpace(paiGong.orNum.ToString()))
                {
                    rsl.Message = "派工单序号不允许为空";
                    return rsl;
                }
                string eDate = DateTime.Parse(paiGong.sDate).AddHours(24).ToString("yyyy-MM-dd HH:mm:ss");
                paiGong.eDate = eDate;
                oper = new OperateModel();
                if (paiGong.id == null || paiGong.id == 0)
                {
                    #region 添加操作
                    string key = getTimeString();
                    paiGong.pKey = key;
                    paiGong.createtime = getNow();
                    paiGong.createuser = userLogin.UserInfo().userCode;
                    paiGong.isDel = 0;
                    paiGong.isFinish = 0;
                    oper.Types = OperateModel.OperateType.Add;
                    oper.Data = paiGong;
                    operList.Add(oper);

                    DbPlanPaiGongSub psub;
                    var pArr = json["pids"].ToString().Split(',');
                    var pgArr = json["gids"].ToString().Split(',');
                    for (int i = 0; i < pArr.Length; i++)
                    {
                        if (!string.IsNullOrWhiteSpace(pArr[i]))
                        {
                            psub = new DbPlanPaiGongSub();
                            psub.pKey = key;
                            psub.ppId = pArr[i];
                            psub.pgId = pgArr[i];
                            psub.isdel = 0;
                            oper = new OperateModel();
                            oper.Data = psub;
                            oper.Types = OperateModel.OperateType.Add;
                            operList.Add(oper);

                            #region 改变生产计划状态
                            DbProductionPlanPro pp = new DbProductionPlanPro();
                            pp.id = int.Parse(pArr[i]);
                            pp.status = "ps-doing";
                            oper = new OperateModel();
                            oper.Data = pp;
                            oper.Types = OperateModel.OperateType.Edit;
                            oper.Conditions = "id";
                            operList.Add(oper);
                            #endregion

                            #region 改变存货工序状态
                            DbPlanGongXu gx = new DbPlanGongXu();
                            gx.id = int.Parse(pgArr[i]);
                            gx.status = "ps-doing";
                            oper = new OperateModel();
                            oper.Data = gx;
                            oper.Types = OperateModel.OperateType.Edit;
                            oper.Conditions = "id";
                            operList.Add(oper);
                            #endregion
                        }
                    }

                    #endregion
                }
                else
                {
                    #region 修改
                    sb.Append("select * from pi_PaiGong_main where id=" + paiGong.id);
                    var user = userLogin.UserInfo();
                    var qTable = cmd.GetDataTable(sb.ToString());
                    if (qTable.Rows.Count < 1)
                    {
                        rsl.Message = "关键参数(dataId)丢失";
                        return rsl;
                    }
                    if (qTable.Rows[0]["createuser"].ToString() != user.userCode)
                    {
                        rsl.Message = "对不起,您无权修改他人数据";
                        return rsl;
                    }
                    #region  判断派工单是否有报工记录
                    sb.Clear();
                    sb.Append("select * from pi_PlanBaogong_main where pKey='" + qTable.Rows[0]["pKey"].ToString() + "' and isDel=0 ");
                    var bgTable = cmd.GetDataTable(sb.ToString());
                    if (bgTable.Rows.Count > 0)
                    {
                        rsl.Message = "当前派工单已有报工记录，暂不支持修改";
                        return rsl;
                    }
                    #endregion
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    oper.Data = paiGong;
                    operList.Add(oper);
                    #endregion
                }




                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 派工任务添加方法
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult AddPaiGongTask(string datas, string list)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            operList = new List<OperateModel>();
            try
            {
                if (string.IsNullOrWhiteSpace(datas) || string.IsNullOrWhiteSpace(list))
                {
                    rsl.Message = "提交数据为空";
                    return rsl;
                }
                operList = new List<OperateModel>();
                string tpKey = getTimeString();//同一派工标识码
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                var jsons = JsonConvert.DeserializeObject<List<JObject>>(list);
                #region 防空值验证
                if (string.IsNullOrWhiteSpace(json["groupCodes"].ToString()))
                {
                    rsl.Message = "生产班组不允许为空";
                    return rsl;
                }
                if (string.IsNullOrWhiteSpace(json["gxCode"].ToString()))
                {
                    rsl.Message = "工序不允许为空";
                    return rsl;
                }
                if (string.IsNullOrWhiteSpace(json["sDate"].ToString()))
                {
                    rsl.Message = "请选择生产日期";
                    return rsl;
                }
                if (json["isNeedIn"] != null)
                {
                    if (string.IsNullOrWhiteSpace(json["wareHouse"].ToString()))
                    {
                        rsl.Message = "请选择入库仓库";
                        return rsl;
                    }
                }
                foreach (var obj in jsons)
                {
                    if (string.IsNullOrWhiteSpace(obj["pgNum"].ToString()))
                    {
                        rsl.Message = "派工数量不允许为空";
                        return rsl;
                    }
                    if (obj["pgNum"].ToString().Equals("0.00"))
                    {
                        rsl.Message = "派工数量不允许为0";
                        return rsl;
                    }
                    if (Convert.ToDecimal(obj["pgNum"].ToString()) < 0)
                    {
                        rsl.Message = "派工数量不允许为负数";
                        return rsl;
                    }
                }
                #endregion

                #region 不允许多个计划派给多个班组
                if (jsons.Count > 1 && json["groupCodes"].ToString().Contains(","))
                {
                    rsl.Message = "不允许多个计划派给多个班组";
                    return rsl;
                }
                #endregion
                DbPlanPaiGong pai; DbProductionPlanPro pp; DbPlanGongXu gx;
                foreach (var obj in jsons)
                {
                    var ppIdArr = obj["id"].ToString().Split(',');  //计划存货id\
                    foreach (string pId in ppIdArr)
                    {
                        if (!string.IsNullOrWhiteSpace(pId))
                        {
                            var groupArr = json["groupCodes"].ToString().Split(',');
                            foreach (string g in groupArr)
                            {
                                if (!string.IsNullOrWhiteSpace(g))
                                {
                                    pai = new DbPlanPaiGong();
                                    pai.createtime = getNow();
                                    pai.createuser = userLogin.UserInfo().userCode;
                                    pai.groupCode = g;
                                    pai.gxCode = json["gxCode"].ToString();
                                    pai.isDel = 0;
                                    pai.number = (Convert.ToDecimal(obj["pgNum"].ToString())
                                        / groupArr.Length).ToString("0.00");
                                    pai.ppId = pId;
                                    pai.isFinish = 0;
                                    if (json["isNeedIn"] != null)
                                    {
                                        pai.isNeedIn = 1;
                                        pai.wareCode = json["wareHouse"].ToString();
                                    }
                                    pai.memo = json["memo"].ToString();
                                    pai.sDate = json["sDate"].ToString();
                                    pai.isUrgent = obj["isUrgent"].ToString();
                                    pai.eDate = DateTime.Parse(json["sDate"].ToString()).AddHours(24).ToString("yyyy-MM-dd HH:mm:ss");
                                    pai.tpKey = tpKey;
                                    pai.tpCode = CreateCodeInfo("TP", "派工界面", 4);
                                    oper = new OperateModel();
                                    oper.Data = pai;
                                    oper.Types = OperateModel.OperateType.Add;
                                    operList.Add(oper);

                                    pp = new DbProductionPlanPro();
                                    pp.id = int.Parse(pId);
                                    pp.status = "ps-doing";
                                    oper = new OperateModel();
                                    oper.Data = pp;
                                    oper.Types = OperateModel.OperateType.Edit;
                                    oper.Conditions = "id";
                                    operList.Add(oper);
                                }
                            }
                        }
                    }
                }


                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                    if (rsl.Result)
                    {
                        operList = new List<OperateModel>();
                        #region 改变生产计划状态
                        foreach (var obj in jsons)
                        {
                            var ppIdArr = obj["id"].ToString().Split(',');  //计划存货id\
                            foreach (string pId in ppIdArr)
                            {
                                gx = new DbPlanGongXu();
                                sb.Clear();
                                sb.Append("select p.id,p.number,Sum(convert(decimal(18,2),pg.number)) number from ");
                                sb.Append("V_ProductionPlan_process p inner join pi_PlanPaiGong_info pg on p.ppId = pg.ppId and ");
                                sb.Append("p.gxCode = pg.gxCode where p.ppid = '" + pId + "' and pg.isDel = 0 and p.gxCode = '");
                                sb.Append(json["gxCode"].ToString() + "' group by p.id,p.number");
                                var table = cmd.GetDataTable(sb.ToString());
                                if (Convert.ToDecimal(table.Rows[0][1].ToString()) == Convert.ToDecimal(table.Rows[0][2].ToString()))
                                    gx.status = "ps-doing";
                                else
                                    gx.status = "ps-prtpg-set";
                                gx.id = int.Parse(table.Rows[0][0].ToString());
                                oper = new OperateModel();
                                oper.Data = gx;
                                oper.Types = OperateModel.OperateType.Edit;
                                oper.Conditions = "id";
                                operList.Add(oper);
                            }
                        }
                        rsl = cmd.MoreUpdate(operList);
                        #endregion
                    }
                    else
                    {
                        return rsl;
                    }
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 织造派工任务添加方法
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult AddZZPaiGongTask(string datas, string list)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            operList = new List<OperateModel>();
            try
            {
                if (string.IsNullOrWhiteSpace(datas) || string.IsNullOrWhiteSpace(list))
                {
                    rsl.Message = "提交数据为空";
                    return rsl;
                }
                operList = new List<OperateModel>();
                string tpKey = getTimeString();//同一派工标识码
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                var jsons = JsonConvert.DeserializeObject<List<JObject>>(list);

                #region 防空值验证
                if (string.IsNullOrWhiteSpace(json["machineCodes"].ToString()))
                {
                    rsl.Message = "生产机台不允许为空";
                    return rsl;
                }
                if (string.IsNullOrWhiteSpace(json["gxCode"].ToString()))
                {
                    rsl.Message = "工序不允许为空";
                    return rsl;
                }
                if (string.IsNullOrWhiteSpace(json["sDate"].ToString()))
                {
                    rsl.Message = "请选择生产日期";
                    return rsl;
                }
                foreach (var obj in jsons)
                {
                    if (string.IsNullOrWhiteSpace(obj["pgNum"].ToString()))
                    {
                        rsl.Message = "派工数量不允许为空";
                        return rsl;
                    }
                    if (obj["pgNum"].ToString().Equals("0.00"))
                    {
                        rsl.Message = "派工数量不允许为0";
                        return rsl;
                    }
                    if (Convert.ToDecimal(obj["pgNum"].ToString()) < 0)
                    {
                        rsl.Message = "派工数量不允许为负数";
                        return rsl;
                    }
                }
                #endregion

                #region 不允许多个计划派给多个机台
                if (jsons.Count > 1 && json["machineCodes"].ToString().Contains(","))
                {
                    rsl.Message = "不允许多个计划派给多个机台";
                    return rsl;
                }
                #endregion

                #region 获取 在 生产日期的 织造派工单 
                sb.Append("select * from pi_PlanPaiGong_info where isDel = 0 and sDate = '" + json["sDate"].ToString() + "' and maCode is not null order by id desc ");//and isFinish = 0
                var table = cmd.GetDataTable(sb.ToString());
                #endregion

                int num = 0; //自定义的生产序号
                if (!string.IsNullOrWhiteSpace(json["orderNum"].ToString()))
                {
                    num = int.Parse(json["orderNum"].ToString());
                }

                #region
                DbPlanPaiGong pai; DbProductionPlanPro pp; DbPlanGongXu gx;
                decimal orderNum = 0; 
                var mNum = new Dictionary<string, decimal>();
                foreach (var obj in jsons)
                {
                    var ppIdArr = obj["id"].ToString().Split(',');  //计划存货id
                    foreach (string pId in ppIdArr)
                    {
                        if (!string.IsNullOrWhiteSpace(pId))
                        {
                            var maArr = json["machineCodes"].ToString().Split(',');
                            foreach (string m in maArr)
                            {
                                if (!string.IsNullOrWhiteSpace(m))
                                {
                                    #region 生产序号
                                    if (!mNum.ContainsKey(m))
                                    {
                                        if (num == 0)
                                        {
                                            //未定义序号
                                            var rows = table.Select(" maCode = '" + m + "'","orderNum desc");
                                            if (rows.Length <= 0)
                                            {
                                                orderNum = 1;
                                            }
                                            else
                                            {
                                                orderNum = decimal.Parse(rows[0]["orderNum"].ToString()) + 1;
                                            }
                                        }
                                        else
                                        {
                                            var rows = table.Select(" maCode = '" + m + "'", "orderNum");

                                            if(num> decimal.Parse(rows[rows.Length-1]["orderNum"].ToString()))
                                            {
                                                //自定义的顺序比派工单数量大
                                                orderNum = num;
                                            }
                                            else
                                            {
                                                //自定义的顺序比派工单数量小 或 相等
                                                orderNum = decimal.Parse(rows[num-1]["orderNum"].ToString());
                                            }


                                        }
                                        mNum.Add(m, orderNum);
                                    }
                                    else
                                    {
                                        //同一个机台派了多个计划
                                        if (num == 0)
                                        {
                                            //未定义序号
                                            orderNum = mNum[m] + 1;
                                        }
                                        else
                                        {
                                            //定义了序号 
                                            orderNum = mNum[m]  - (decimal)0.001;
                                        }
                                    }
                                    #endregion

                                    #region 派工单添加
                                    pai = new DbPlanPaiGong();
                                    pai.createtime = getNow();
                                    pai.createuser = userLogin.UserInfo().userCode;
                                    pai.maCode = m;
                                    pai.gxCode = json["gxCode"].ToString();
                                    pai.isDel = 0;
                                    pai.number = (Convert.ToDecimal(obj["pgNum"].ToString())
                                        / maArr.Length).ToString("0.00");
                                    pai.ppId = pId;
                                    pai.isFinish = 0;
                                    pai.orderNum = orderNum;
                                    pai.memo = json["memo"].ToString();
                                    pai.sDate = json["sDate"].ToString();
                                    pai.isUrgent = obj["isUrgent"].ToString();
                                    pai.eDate = DateTime.Parse(json["sDate"].ToString()).AddHours(24).ToString("yyyy-MM-dd HH:mm:ss");
                                    pai.tpKey = tpKey;
                                    pai.tpCode = CreateCodeInfo("TP", "派工界面", 4);
                                    oper = new OperateModel();
                                    oper.Data = pai;
                                    oper.Types = OperateModel.OperateType.Add;
                                    operList.Add(oper);
                                    #endregion

                                    #region 计划子表状态修改
                                    pp = new DbProductionPlanPro();
                                    pp.id = int.Parse(pId);
                                    pp.status = "ps-doing";
                                    oper = new OperateModel();
                                    oper.Data = pp;
                                    oper.Types = OperateModel.OperateType.Edit;
                                    oper.Conditions = "id";
                                    operList.Add(oper);
                                    #endregion

                                }
                            }
                        }
                    }
                }
                #endregion

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                    if (rsl.Result)
                    {
                        operList = new List<OperateModel>();
                        #region 改变生产计划状态
                        foreach (var obj in jsons)
                        {
                            var ppIdArr = obj["id"].ToString().Split(',');  //计划存货id\
                            foreach (string pId in ppIdArr)
                            {
                                gx = new DbPlanGongXu();
                                sb.Clear();
                                sb.Append("select p.id,p.number,Sum(convert(decimal(18,2),pg.number)) number from ");
                                sb.Append("V_ProductionPlan_process p inner join pi_PlanPaiGong_info pg on p.ppId = pg.ppId and ");
                                sb.Append("p.gxCode = pg.gxCode where p.ppid = '" + pId + "' and pg.isDel = 0 and p.gxCode = '");
                                sb.Append(json["gxCode"].ToString() + "' group by p.id,p.number");
                                table = cmd.GetDataTable(sb.ToString());
                                if (Convert.ToDecimal(table.Rows[0][1].ToString()) == Convert.ToDecimal(table.Rows[0][2].ToString()))
                                    gx.status = "ps-doing";
                                else
                                    gx.status = "ps-prtpg-set";
                                gx.id = int.Parse(table.Rows[0][0].ToString());
                                oper = new OperateModel();
                                oper.Data = gx;
                                oper.Types = OperateModel.OperateType.Edit;
                                oper.Conditions = "id";
                                operList.Add(oper);
                            }
                        }
                        rsl = cmd.MoreUpdate(operList);
                        #endregion
                    }
                    else
                    {
                        return rsl;
                    }
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 根据id获取排产计划信息
        /// </summary>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ReturnResult GetPaiChanById(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from pi_PaiGong_main where id=" + dataId);
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 删除派工任务
        /// </summary>
        /// <param name="dataId">派工单号</param>
        /// <returns></returns>
        public ReturnResult DelPaiChanById(string dataId)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                StringBuilder sb = new StringBuilder();
                #region 判断派工单是否报工
                sb.Append("select * from pi_PlanBaogong_main where isdel = 0 and pKey = '" + dataId + "' ");
                var bgTable = cmd.GetDataTable(sb.ToString());
                if (bgTable.Rows.Count > 0)
                {
                    rsl.Message = "此派工单已报工，暂不支持删除";
                    return rsl;
                }
                #endregion

                #region  删派工记录
                DbPlanPaiGong pg = new DbPlanPaiGong();
                pg.isDel = 1;
                pg.tpCode = dataId;
                pg.delMsg = userLogin.UserInfo().userCode + "," + getNow();
                oper = new OperateModel();
                oper.Data = pg;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "tpCode";
                operList.Add(oper);
                #endregion

                #region  获取派工单ppid 和gxCode
                var ppid = ""; var gxCode = "";
                sb.Clear();
                sb.Append("select ppId,gxCode from pi_PlanPaiGong_info where tpCode ='" + dataId + "'");
                var pTable = cmd.GetDataTable(sb.ToString());
                if (pTable.Rows.Count > 0)
                {
                    ppid = pTable.Rows[0]["ppId"].ToString();
                    gxCode = pTable.Rows[0]["gxCode"].ToString();
                }
                else
                {
                    rsl.Message = "数据错误，缺少派工单对应存货信息";
                    return rsl;
                }
                #endregion
                #region  如果计划存货没有派工信息，则修改存货状态为ps-pg-set（待派工）
                sb.Clear();
                sb.Append("select * from pi_PlanPaiGong_info where isdel = 0 and ppId='" + ppid + "' and tpCode != '" + dataId + "'");
                var pgTable = cmd.GetDataTable(sb.ToString());
                if (pgTable.Rows.Count < 1)
                {
                    DbProductionPlanPro pro = new DbProductionPlanPro();
                    pro.id = Convert.ToInt32(ppid);
                    pro.status = "ps-pg-set";
                    oper = new OperateModel();
                    oper.Data = pro;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    operList.Add(oper);
                }
                #endregion
                #region  如果工序信息没有派工信息，则修改工序(process)为ps-dsc（待派工）
                sb.Append(" and gxCode = '" + gxCode + "'");
                var prtable = cmd.GetDataTable(sb.ToString());
                if (prtable.Rows.Count < 1)
                {
                    DbPlanGongXu gx = new DbPlanGongXu();
                    gx.ppId = ppid;
                    gx.gxCode = gxCode;
                    gx.status = "ps-dsc";
                    oper = new OperateModel();
                    oper.Data = gx;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "ppId,gxCode";
                    operList.Add(oper);
                }
                #endregion

                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 修改派工任务状态
        /// </summary>
        /// <param name="dataId">排产数据id</param>
        /// <param name="status">完成状态</param>
        /// <returns></returns>
        public ReturnResult UpdatePaiChanStatusById(string dataId, int status, string type, string result, string memo)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                DbPlanPaiGong pg = new DbPlanPaiGong();
                pg.tpCode = dataId;
                pg.isFinish = status;
                oper = new OperateModel();
                oper.Data = pg;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "tpCode";
                operList.Add(oper);

                //向审批操作纪录表中添加记录
                DbApproveRecord ar = new DbApproveRecord();
                ar.businessType = type;
                ar.businessCode = dataId;
                ar.result = result;
                ar.createtime = getNow();
                ar.createuser = userLogin.UserInfo().userCode;
                ar.memo = memo;
                oper = new OperateModel();
                oper.Types = OperateModel.OperateType.Add;
                oper.Data = ar;
                operList.Add(oper);

                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 创建计划备料单
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <param name="rowNo">行号</param>
        /// <param name="id">计划存货id</param>
        /// <param name="datas">数据</param>
        /// <param name="userCodes">人员</param>
        /// <param name="userNames">人员名称</param>
        /// <param name="memo">备注</param>
        /// <param name="tzzh">是否是组合的套装</param>
        /// <returns></returns>
        public ReturnResult AddMaterialOutRecords(string plCode, string rowNo, string id, List<Dictionary<string, string>> datas, string userCodes, string userNames, string memo, string tzzh)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                if (datas.Count < 1)
                {
                    rsl.Message = "没有要保存的数据";
                    return rsl;
                }
                #region
                StringBuilder sb = new StringBuilder();
                sb.Append("select proCode, cu_yanse, cu_shangbiao, sum(CONVERT(decimal(18, 2), number)) number ");
                sb.Append("from pi_ProductionPlan_products where id in (" + id + ") group by proCode, cu_yanse, cu_shangbiao");
                var pTable = cmd.GetDataTable(sb.ToString());//各存货计划数量

                var blTable = new DataTable();
                for (var i = 0; i < plCode.Split(',').Length; i++)
                {
                    sb.Clear();
                    sb.Append("select proCode,cu_color,cu_shangbiao,Sum(convert(decimal(18,2 ),number)) number ");
                    sb.Append("from pi_PaiGong_material_sub s inner join pi_PaiGong_material_main m on m.pmCode = s.pmCode ");
                    sb.Append("where s.isdel = 0 and plCode = '" + plCode.Split(',')[i] + "' and rowNo = '" + rowNo.Split(',')[i]);
                    sb.Append("' group by proCode, cu_color, cu_color, cu_shangbiao ");
                    blTable.Merge(cmd.GetDataTable(sb.ToString()));
                }
                string codeLength = Tools.ConfigReader.Reader["CodeLength"];
                string blCode = CreateCodeInfo("BL", "备料单号", int.Parse(codeLength));
                string bltime = getNow();
                #region 备料主表
                DbPGMaterialMain mater;
                mater = new DbPGMaterialMain();
                mater.pmCode = blCode;
                mater.plCode = plCode;
                mater.rowNo = rowNo;
                mater.status = "bl-nout";
                mater.isdel = 0;
                mater.createtime = bltime;
                mater.createuser = userLogin.UserInfo().userCode;
                mater.users = userNames;
                mater.memo = memo;
                mater.istz = tzzh;
                oper = new OperateModel();
                oper.Data = mater;
                oper.Types = OperateModel.OperateType.Add;
                operList.Add(oper);
                #endregion

                #region 备料子表
                DbPGMaterialSub sub = new DbPGMaterialSub();
                foreach (var obj in datas)
                {
                    #region  获取计划数量
                    decimal plNum = 0;
                    var plList = pTable.Select("proCode='" + obj["proCode"].ToString() + "' and cu_yanse='" +
                         obj["color"].ToString() + "' and cu_shangbiao='" + obj["shangbiao"].ToString() + "'");
                    if (plList.Length > 0)
                    {
                        plNum = Convert.ToDecimal(plList[0]["number"].ToString());
                    }
                    else
                    {
                        foreach (DataRow dr in pTable.Rows)
                        {
                            plNum += Convert.ToDecimal(dr["number"].ToString());
                        }
                    }
                    #endregion

                    #region 判断存货备料数量是不是大于计划数量
                    var blList = blTable.Select("proCode='" + obj["proCode"].ToString() + "' and cu_color='" +
                         obj["color"].ToString() + "' and cu_shangbiao='" + obj["shangbiao"].ToString() + "'");
                    if (blList.Length > 0)
                    {
                        var blnum = Convert.ToDecimal(blList[0]["number"].ToString());//存货已备料数量
                        var total = blnum + Convert.ToDecimal(obj["number"].ToString());
                        if (total > plNum)
                        {
                            rsl.Message = "该计划" + obj["proCode"].ToString() + "-" + obj["color"].ToString() + "-" +
                                obj["shangbiao"].ToString() + "</br> " +
                                "已添加备货数量" + blnum + ",继续备货将超过计划数" + plNum;
                            return rsl;
                        }
                    }
                    else
                    {
                        string number = "0";
                        if (obj.ContainsKey("number") && string.IsNullOrWhiteSpace(obj["number"].ToString()))
                        {
                            number = obj["number"].ToString();
                        }
                        if (Convert.ToDecimal(number) > plNum)
                        {
                            rsl.Message = "该计划" + obj["proCode"].ToString() + "-" + obj["color"].ToString() + "-" +
                                obj["shangbiao"].ToString() + "</br> " +
                                "录入的备货数量" + obj["number"].ToString() + ">计划数" + plNum;
                            return rsl;
                        }
                    }
                    #endregion

                    sub = new DbPGMaterialSub();
                    sub.pmCode = blCode;
                    sub.wareCode = obj["wareCode"].ToString();
                    if (obj["positionCode"] != null)
                        sub.positionCode = obj["positionCode"].ToString();
                    sub.proCode = obj["proCode"].ToString();
                    sub.number = obj["number"].ToString();
                    sub.cu_color = obj["color"].ToString();
                    sub.cu_shangbiao = obj["shangbiao"].ToString();
                    sub.isdel = 0;
                    sub.status = "bl-nout";
                    oper = new OperateModel();
                    oper.Data = sub;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);
                }
                #endregion

                ////后期需要对接U8接口，生成材料出库单
                if (operList.Count > 0)
                {
                    if (operList.Count == 1)
                    {
                        rsl.Message = "请检查领料数量";
                        return rsl;
                    }
                    rsl = cmd.MoreUpdate(operList);
                    if (!string.IsNullOrEmpty(userCodes))
                        ding.sendDingMsg("BL", plCode, userCodes, "计划" + plCode + "新增备货需求，请及时备货！", userLogin.UserInfo().userCode);
                }
                else
                {
                    rsl.Message = "没有数据";
                }
                #endregion
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 报工数据保存方法
        /// </summary>
        /// <param name="datas"></param>
        /// <param name="pKey">派工单号</param>
        /// <returns></returns>
        public ReturnResult SaveBaoGong(string datas, string pKey, string isFrom)
        {
            rsl = new ReturnResult();
            try
            {
                operList = new List<OperateModel>();
                StringBuilder sb = new StringBuilder();
                var jsons = JsonConvert.DeserializeObject<List<JObject>>(datas);
                double numTotal = 0;//报工数总额
                double yNumTotal = 0;//报工合格数总额
                DbPlanPaiGong pg;
                DbPlanGongXu pgx;
                var ppid = "";//生产计划子表中的id
                var pgNumber = 0.0;//派工单数量
                var plNumber = 0.0;//计划数量
                var bgPriceMes = "";//报工单价为0提示

                var wareCode = "";

                var plType = "";

                if (string.IsNullOrWhiteSpace(datas) || jsons.Count < 1)
                {
                    rsl.Message = "没有任何保存数据";
                    return rsl;
                }

                #region 派工单相关信息
                sb.Append("select pg.* ,pro.plCode plCodes,pro.prlCode,pro.number plNumber,p.plType from pi_PlanPaiGong_info pg ");
                sb.Append("inner join pi_ProductionPlan_products pro on pro.id =pg.ppId ");
                sb.Append("left join pi_ProductionPlan_info p on p.plCode=pro.plCode ");
                sb.Append("where pg.isdel=0 and tpCode='" + pKey + "'");
                var pgTable = cmd.GetDataTable(sb.ToString());
                if (pgTable.Rows.Count < 1)
                {
                    rsl.Message = "派工单号不存在";
                    return rsl;
                }
                else
                {
                    plType = pgTable.Rows[0]["plType"].ToString();//计划类型

                    if (pgTable.Rows[0]["isFinish"].ToString() == "1")
                    {
                        rsl.Message = "该派工单已完成，系统不允许进行报工";
                        return rsl;
                    }
                    ppid = pgTable.Rows[0]["ppId"].ToString();//派工单关联的存货信息id

                    if (pgTable.Rows[0]["isNeedIn"].ToString() == "1")
                    {
                        wareCode = pgTable.Rows[0]["wareCode"].ToString();//入库仓库
                    }
                }
                #endregion

                #region 补货改标配置参数
                sb.Clear();
                sb.Append("select parValue from sys_parameters_info where parCode = 'rs_ct_config'");
                var dt = cmd.GetDataTable(sb.ToString());
                if (dt.Rows.Count < 0)
                {
                    rsl.Message = "缺少补货改标配置参数";
                    return rsl;
                }
                var configString = dt.Rows[0]["parValue"].ToString();
                var rc_config = JsonConvert.DeserializeObject<Rs_Ct_Config>(configString);

                var checkGXs = "";
                foreach (var gxs in rc_config.gx)
                {
                    checkGXs += "'" + gxs + "',";
                }
                checkGXs = checkGXs.TrimEnd(',');//涉及到补货改标的工序

                #endregion

                pgNumber = Convert.ToDouble(pgTable.Rows[0]["number"].ToString());
                plNumber = Convert.ToDouble(pgTable.Rows[0]["plNumber"].ToString());
                sb.Clear();
                sb.Append("select * from fun_GxPrice_info ");
                sb.Append("where isdel=0 and cgxCode='" + pgTable.Rows[0]["gxCode"] + "'");
                var wgTable = cmd.GetDataTable(sb.ToString());//获取报工工序的绩效单价
                #region 生产报工
                string bgCode = getTimeString();
                double yTotal = 0, nTotal = 0;
                var createuser = "";
                if (jsons[0].Property("createuser") != null)
                {
                    if (!string.IsNullOrWhiteSpace(jsons[0]["createuser"].ToString()))
                    {
                        createuser = jsons[0]["createuser"].ToString();
                    }
                    else
                    {
                        rsl.Message = "未获取到移动端登陆人员信息";
                        return rsl;
                    }
                }
                else
                {
                    createuser = userLogin.UserInfo().userCode;
                }

                #region 修改数据
                var defNumber = jsons[0]["number"].ToString();//输入的合格数
                var defnNumber = jsons[0]["disNumber"].ToString();//输入的不合格数
                //var defNumber = jsons[0]["yNum"].ToString();//输入的合格数
                //var defnNumber = jsons[0]["nNum"].ToString();//输入的不合格数
                var temyTotal = 0.0;
                var temnTotal = 0.0;
                foreach (var obj in jsons)
                {
                    string yNum = "0", nNum = "0";
                    if (!string.IsNullOrWhiteSpace(obj["yNum"].ToString()))
                    {
                        yNum = obj["yNum"].ToString();
                    }
                    if (!string.IsNullOrWhiteSpace(obj["nNum"].ToString()))
                    {
                        nNum = obj["nNum"].ToString();
                    }
                    temyTotal += double.Parse(yNum);
                    temnTotal += double.Parse(nNum);
                }
                var temcY = Math.Round(double.Parse(defNumber) - temyTotal, 2);
                var temcN = Math.Round(double.Parse(defnNumber) - temnTotal, 2);
                rsl = this.updateNum(jsons, temcY, "yNum");
                if (!rsl.Result)
                {
                    return rsl;
                }
                rsl = this.updateNum(jsons, temcN, "nNum");
                if (!rsl.Result)
                {
                    return rsl;
                }
                rsl.Result = false;//清空状态
                #endregion

                #region 子表 及绩效
                DbPlanBaogongSub bg_sub;
                DbemployeeWage wage;
                foreach (var obj in jsons)
                {
                    if (obj.Count < 1)
                    {
                        rsl.Message = "请先选择员工";
                        return rsl;
                    }
                    string yNum = "0", nNum = "0";
                    if (!string.IsNullOrWhiteSpace(obj["yNum"].ToString()))
                    {
                        yNum = obj["yNum"].ToString();
                        numTotal += double.Parse(yNum);
                        yNumTotal += double.Parse(yNum);
                    }
                    if (!string.IsNullOrWhiteSpace(obj["nNum"].ToString()))
                    {
                        nNum = obj["nNum"].ToString();
                        numTotal += double.Parse(nNum);
                    }
                    yTotal += double.Parse(yNum);
                    nTotal += double.Parse(nNum);
                    bg_sub = new DbPlanBaogongSub();
                    bg_sub.createtime = getNow();
                    bg_sub.createuser = createuser;
                    bg_sub.happenDate = getNowDate();
                    bg_sub.isdel = 0;
                    bg_sub.nNum = nNum;
                    bg_sub.yNum = yNum;
                    bg_sub.isFrom = isFrom;
                    bg_sub.bgCode = bgCode;
                    bg_sub.gxCode = pgTable.Rows[0]["gxCode"].ToString();
                    bg_sub.userCode = obj["userCode"].ToString();
                    oper = new OperateModel();
                    oper.Data = bg_sub;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);

                    #region 工序存在绩效单价则需生成人员绩效
                    if (wgTable.Rows.Count > 0)
                    {
                        if (wgTable.Rows[0]["yPrice"].ToString().Equals("0"))
                        {
                            bgPriceMes = "当前报工工艺绩效单价为0，请联系相关负责人维护单价！";
                        }
                        wage = new DbemployeeWage();
                        wage.bgType = "BG";
                        wage.createtime = getNow();
                        wage.createuser = createuser;
                        wage.dataId = pKey;
                        wage.gxCode = pgTable.Rows[0]["gxCode"].ToString();
                        wage.happenDate = obj["happenDate"].ToString();
                        wage.isdel = 0;
                        wage.userCode = obj["userCode"].ToString();
                        wage.status = "approving";
                        wage.memo = "生产报工绩效";
                        wage.nNum = nNum;
                        wage.yNum = yNum;
                        wage.plCode = pgTable.Rows[0]["plCodes"].ToString();
                        wage.uPrice = string.Format("{0}/{1}", wgTable.Rows[0]["yPrice"].ToString(), wgTable.Rows[0]["nPrice"].ToString());
                        wage.wType = "BG";
                        wage.bgCode = bgCode;
                        wage.total = (double.Parse(wgTable.Rows[0]["yPrice"].ToString()) * double.Parse(yNum) + double.Parse(wgTable.Rows[0]["nPrice"].ToString()) * double.Parse(nNum)).ToString();
                        oper = new OperateModel();
                        oper.Data = wage;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                    }

                    #endregion

                }
                #endregion
                if (double.Parse(defNumber) != yTotal)
                {
                    rsl.Result = false;
                    rsl.Message = "人员的总合格数与录入的报工总合格数不相等";
                    return rsl;
                }
                if (double.Parse(defnNumber) != nTotal)
                {
                    rsl.Result = false;
                    rsl.Message = "人员的总不合格数与录入的报工总不合格数不相等";
                    return rsl;
                }
                #region 主表
                DbPlanBaogongMain bg_main;
                bg_main = new DbPlanBaogongMain();
                bg_main.bgCode = bgCode;
                bg_main.bgType = "BG";
                bg_main.nNum = nTotal.ToString();
                bg_main.yNum = yTotal.ToString();
                bg_main.memo = "生产报工";
                bg_main.happenDate = jsons[0]["happenDate"].ToString();
                bg_main.createtime = getNow();
                bg_main.createuser = createuser;
                bg_main.gxCode = pgTable.Rows[0]["gxCode"].ToString();
                bg_main.pKey = pKey;
                bg_main.plCodes = pgTable.Rows[0]["plCodes"].ToString();
                bg_main.isDel = 0;
                bg_main.isFrom = isFrom;
                if (!string.IsNullOrWhiteSpace(ppid))
                {
                    bg_main.ppId = ppid;
                }
                oper = new OperateModel();
                oper.Data = bg_main;
                oper.Types = OperateModel.OperateType.Add;
                operList.Add(oper);
                #endregion

                #region 入库任务
                if (!string.IsNullOrWhiteSpace(wareCode))
                {
                    rsl = addInKuInfo(bgCode,pKey, wareCode, yTotal.ToString(), createuser, ref operList);

                    if (!rsl.Result)
                    {
                        return rsl;
                    }
                    rsl.Result = false;
                }
                #endregion

                #region 补货改标

                if (nTotal > 0)
                {
                    // 添加不合格信息，用于补货改标统计
                    rsl = UnqualifiedInfo(
                         pgTable.Rows[0]["gxCode"].ToString(),
                         nTotal.ToString(),
                         pKey,
                         bgCode,
                         createuser,
                         ref operList);

                    if (!rsl.Result)
                    {
                        return rsl;
                    }
                    rsl.Result = false;
                }


                #endregion 补货改标

                string bNum = "1", bnNum = "0", msg = "", bgxCode = "";
                bool gxIsEnd = false;//是否为最后一道工序
                this.CheckBackGxYnum(pKey, ref bNum, ref bnNum, ref msg, ref gxIsEnd, ref bgxCode);
                if (string.IsNullOrWhiteSpace(bNum))
                {
                    rsl.Message = msg;
                    return rsl;
                }
                #endregion

                #region 派工单是否完成
                sb.Clear();
                sb.Append("select isnull(sum(CONVERT(decimal(18,2),yNum)),0) yNum,isnull(sum(CONVERT(decimal(18,2),nNum)),0) nNum from pi_PlanBaogong_main ");
                sb.Append("where pkey='" + pKey + "' and isdel=0 and gxCode='" + pgTable.Rows[0]["gxCode"].ToString() + "'");
                var pgrTable = cmd.GetDataTable(sb.ToString());//获取该派工单全部的报工数据

                sb.Clear();
                sb.Append("select * from pi_ProductionPlan_process where ppId='" + ppid + "' and gxCode='" + pgTable.Rows[0]["gxCode"].ToString() + "'");
                var table = cmd.GetDataTable(sb.ToString());  //计划工序表
                var parentGx = "";
                if (table.Rows.Count > 0)
                {
                    parentGx = table.Rows[0]["parentCode"].ToString();
                    pgx = new DbPlanGongXu();
                    pgx.id = int.Parse(table.Rows[0]["id"].ToString());
                }
                else
                {
                    rsl.Message = "数据错误，找不到派工单对应的工艺";
                    return rsl;
                }

                if (pgrTable.Rows.Count > 0 && pgrTable.Rows[0]["yNum"] != null && !string.IsNullOrWhiteSpace(pgrTable.Rows[0]["yNum"].ToString()))
                {
                    numTotal = double.Parse(pgrTable.Rows[0]["yNum"].ToString()) + double.Parse(pgrTable.Rows[0]["nNum"].ToString()) + numTotal;
                    yNumTotal = double.Parse(pgrTable.Rows[0]["yNum"].ToString()) + yNumTotal;//合格数总数
                }

                #region 涉及到改标的工序 比较合格数和派工数（上道工序合格数）
                if (checkGXs.Contains(parentGx))
                {
                    if (double.Parse(bNum) < yNumTotal)
                    {
                        rsl.Message = "此工序报工合格数不得大于上道工序报工合格数：</br>" + bNum;
                        return rsl;
                    }
                    if (pgNumber < yNumTotal)
                    {
                        rsl.Message = "此工序报工合格数不得大于派工数：</br>" + bNum;
                        return rsl;
                    }
                }
                else
                {
                    if (double.Parse(bNum) < numTotal)
                    {
                        rsl.Message = "此工序报工总数不得大于上道工序报工合格数：</br>" + bNum;
                        return rsl;
                    }
                    if (pgNumber < numTotal)
                    {
                        rsl.Message = "此工序报工总数不得大于派工数：</br>" + bNum;
                        return rsl;
                    }
                }
                #endregion


                if (numTotal >= double.Parse(pgTable.Rows[0]["number"].ToString()))
                {
                    if ( (checkGXs.Contains(parentGx) && yNumTotal >= double.Parse(pgTable.Rows[0]["number"].ToString()))  || !checkGXs.Contains(parentGx) )
                    {
                        pg = new DbPlanPaiGong();
                        pg.tpCode = pKey;
                        pg.isFinish = 1;
                        pg.finishtime = getNow();
                        oper = new OperateModel();
                        oper.Data = pg;
                        oper.Conditions = "tpCode";
                        oper.Types = OperateModel.OperateType.Edit;
                        operList.Add(oper);

                        //修改工序状态
                        pgx.status = "ps-finish";
                    }
                    else
                    {
                        pgx.status = "ps-doing";
                    }

                    //if (checkGXs.Contains(parentGx))
                    //{
                    //    //如果当前报工工序涉及到补货改标

                    //    if(yNumTotal>= double.Parse(pgTable.Rows[0]["number"].ToString()))
                    //    {
                    //        //判断合格数是否>=派工数
                    //        pg = new DbPlanPaiGong();
                    //        pg.tpCode = pKey;
                    //        pg.isFinish = 1;
                    //        pg.finishtime = getNow();
                    //        oper = new OperateModel();
                    //        oper.Data = pg;
                    //        oper.Conditions = "tpCode";
                    //        oper.Types = OperateModel.OperateType.Edit;
                    //        operList.Add(oper);

                    //        //修改工序状态
                    //        pgx.status = "ps-finish";
                    //    }
                    //    else
                    //    {
                    //        pgx.status = "ps-doing";
                    //    }
                    //}
                    //else
                    //{
                    //    pg = new DbPlanPaiGong();
                    //    pg.tpCode = pKey;
                    //    pg.isFinish = 1;
                    //    pg.finishtime = getNow();
                    //    oper = new OperateModel();
                    //    oper.Data = pg;
                    //    oper.Conditions = "tpCode";
                    //    oper.Types = OperateModel.OperateType.Edit;
                    //    operList.Add(oper);

                    //    //修改工序状态
                    //    pgx.status = "ps-finish";
                    //}
                    
                }
                else
                {
                    pgx.status = "ps-doing";
                }
                oper = new OperateModel();
                oper.Data = pgx;
                oper.Conditions = "id";
                oper.Types = OperateModel.OperateType.Edit;
                operList.Add(oper);

                #endregion

                #region 判断当前工序的下一道工序大类是否允许报工
                var nextParentGx = "";
                getNextGx(ppid, pgTable.Rows[0]["gxCode"].ToString(), ref nextParentGx);
                if (!string.IsNullOrWhiteSpace(nextParentGx))
                {
                    sb.Clear();
                    sb.Append("select * from pi_ProductionPlan_process where 1=1 and ppId='" + ppid + "' and parentCode='" + nextParentGx + "'");
                    sb.Append(" and isnull(canBg,0)<>1 ");
                    var gxtable = cmd.GetDataTable(sb.ToString());  //计划工序表
                    if (gxtable.Rows.Count > 0)
                    {
                        oper = new OperateModel();
                        var planProcess = new DbPlanGongXu();
                        planProcess.ppId = ppid;
                        planProcess.parentCode = nextParentGx;
                        planProcess.canBg = 1;
                        oper = new OperateModel();
                        oper.Data = planProcess;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "ppId,parentCode";
                        operList.Add(oper);
                    }
                }
                #endregion

                #region  判断生产计划是否完成
                var dic = new Dictionary<string, object>();
                dic["ppid"] = ppid.ToString();
                dic["parentGx"] = parentGx.ToString();
                dic["yTotal"] = yTotal;
                dic["nTotal"] = nTotal;
                dic["plNumber"] = plNumber;

                //如果报工工序涉及到补货改标的工序，改变计划状态时只看合格数是否足够
                var onlyY = false; 
                if (checkGXs.Contains(parentGx))
                {
                    onlyY = true;
                }

                //包装计划不按照是否报工完成来判定计划是否完成 （旧）
                //包装计划如果未勾选是否包装，则报完工计划就完成，不需要打码 （新）
                sb.Clear();
                sb.Append("select * from V_ProductionPlan_products where 1=1 and id=" + ppid  );   //+ "  and plType<>'P-Pack' "
                var plDt = cmd.GetDataTable(sb.ToString());
                if (plDt != null && plDt.Rows.Count > 0)
                {
                    if( (plDt.Rows[0]["plType"].ToString()=="P-Pack"  && plDt.Rows[0]["needPack"].ToString() == "0") ||
                        plDt.Rows[0]["plType"].ToString() != "P-Pack")
                    {
                        ChanagePlanStatus(gxIsEnd, dic, ref operList,onlyY);
                    }

                    //ChanagePlanStatus(gxIsEnd, dic, ref operList);
                }
                #endregion

                #region 如果是改标计划，向任务中心表中新增一条记录
                var toUser = "";//改标计划负责人
                var prlCode = "";//改标计划的原计划编码

                if (plType == "P-ChangeTag")
                {
                    #region 获取改标计划负责人 
                    sb.Clear();
                    sb.Append("select * from sys_TaskCenter_info where relationOrder = '"+ pgTable.Rows[0]["prlCode"].ToString() +"'");
                    var taskTable = cmd.GetDataTable(sb.ToString()); //改标计划相关的改标申请单

                    var rids = taskTable.Rows[0]["businessId"].ToString().TrimEnd(',');
                    rids = rids.Replace("'", string.Empty);
                    toUser = taskTable.Rows[0]["relationPeople"].ToString();
                    #endregion

                    #region 获取改标计划关联的原计划
                    sb.Clear();
                    sb.Append("select r.pgCode,pro.prlCode from pi_reStock_info r ");
                    sb.Append("inner join pi_PlanPaiGong_info p on p.tpCode = r.pgCode  and r.isdel = 0 ");
                    sb.Append("inner join pi_ProductionPlan_products pro on p.ppId=pro.id ");
                    sb.Append("where r.id in ("+ rids + ") ");
                    var plTable = cmd.GetDataTable(sb.ToString()); //改标计划相关的原计划编码 prlCode
                    
                    foreach (DataRow dr in plTable.Rows)
                    {
                        prlCode+="'"+dr["prlCode"].ToString()+"',";
                    }
                    #endregion

                    TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                    var tms = Convert.ToInt64(ts.TotalMilliseconds).ToString();
                    var taskCode = pub.getTimesString();

                    DbTaskCenter task = new DbTaskCenter();
                    task.id = tms;
                    task.businessType = "CTFinish";
                    task.businessId = "'"+ppid+"',";//改标计划id
                    task.toUser = toUser;
                    task.contents = datas;
                    task.createtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    task.createuser = createuser;
                    task.isFinish = 0;
                    task.memo = "改标计划报工提醒原计划可报工";
                    task.taskCode = taskCode;
                    task.relationOrder = prlCode;//原计划编码

                    oper = new OperateModel();
                    oper.Data = task;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);
                }
                #endregion

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                    if (rsl.Result)
                    {
                        if (!string.IsNullOrWhiteSpace(bgPriceMes))
                            rsl.Message = bgPriceMes;
                        //发送钉钉消息
                        if (plType == "P-ChangeTag")
                        {
                            ding.sendDingMsg("CTFinish", pgTable.Rows[0]["prlCode"].ToString(), toUser, "计划" + prlCode.Replace("'",string.Empty) +
                                "新增报工记录：合格（" + yTotal + "条），不合格（" + nTotal + "条），可继续报工！", createuser);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 织造计划 报工数据保存方法
        /// </summary>
        /// <param name="datas"></param>
        /// <param name="maCode">机台号</param>
        /// <returns></returns>
        public ReturnResult SaveZZBaoGong(string datas, string maCode, string isFrom)
        {
            rsl = new ReturnResult();
            try
            {
                operList = new List<OperateModel>();
                StringBuilder sb = new StringBuilder();
                var jsons = JsonConvert.DeserializeObject<List<JObject>>(datas);
                double numTotal = 0;//报工数总额
                double yNumTotal = 0;//报工合格数总额
                DbPlanPaiGong pg;
                DbPlanGongXu pgx;
                var ppid = "";//生产计划子表中的id
                var pgNumber = 0.0;//派工单数量
                var plNumber = 0.0;//计划数量
                var plType = ""; 
                var pKey = "";

                if (string.IsNullOrWhiteSpace(datas) || jsons.Count < 1)
                { 
                    rsl.Message = "没有任何保存数据";
                    return rsl;
                } 

                #region 机台派工单信息
                sb.Append("select top 1 * from V_PlanPaiChan_info where isFinish = 0 and maCode = '" + maCode + "' order by sDate,orderNum ");
                var pgTable = cmd.GetDataTable(sb.ToString());
                if (pgTable.Rows.Count < 1)
                {
                    rsl.Message = "当前机台不存在派工任务";
                    return rsl;
                }
                else
                {
                    plType = pgTable.Rows[0]["plType"].ToString();//计划类型
                    ppid = pgTable.Rows[0]["ppId"].ToString();//派工单关联的存货信息id
                    pKey = pgTable.Rows[0]["pKey"].ToString();//派工单号
                }
                #endregion
                pgNumber = Convert.ToDouble(pgTable.Rows[0]["number"].ToString());
                plNumber = Convert.ToDouble(pgTable.Rows[0]["plNumber"].ToString());

                #region 生产报工
                string bgCode = getTimeString();
                double yTotal = 0, nTotal = 0;
                var createuser = "";
                if (jsons[0].Property("createuser") != null)
                {
                    if (!string.IsNullOrWhiteSpace(jsons[0]["createuser"].ToString()))
                    {
                        createuser = jsons[0]["createuser"].ToString();
                    }
                    else
                    {
                        rsl.Message = "未获取到移动端登陆人员信息";
                        return rsl;
                    }
                }
                else
                {
                    createuser = userLogin.UserInfo().userCode;
                }

                #region 修改数据
                var defNumber = jsons[0]["number"].ToString();//输入的合格数
                var defnNumber = jsons[0]["disNumber"].ToString();//输入的不合格数
                var temyTotal = 0.0;
                var temnTotal = 0.0;
                foreach (var obj in jsons)
                {
                    string yNum = "0", nNum = "0";
                    if (!string.IsNullOrWhiteSpace(obj["yNum"].ToString()))
                    {
                        yNum = obj["yNum"].ToString();
                    }
                    if (!string.IsNullOrWhiteSpace(obj["nNum"].ToString()))
                    {
                        nNum = obj["nNum"].ToString();
                    }
                    temyTotal += double.Parse(yNum);
                    temnTotal += double.Parse(nNum);
                }
                var temcY = Math.Round(double.Parse(defNumber) - temyTotal, 2);
                var temcN = Math.Round(double.Parse(defnNumber) - temnTotal, 2);
                rsl = this.updateNum(jsons, temcY, "yNum");
                if (!rsl.Result)
                {
                    return rsl;
                }
                rsl = this.updateNum(jsons, temcN, "nNum");
                if (!rsl.Result)
                {
                    return rsl;
                }
                rsl.Result = false;//清空状态
                #endregion

                #region 报工子表 
                DbPlanBaogongSub bg_sub;
                foreach (var obj in jsons)
                {
                    if (obj.Count < 1)
                    {
                        rsl.Message = "请先选择员工";
                        return rsl;
                    }
                    string yNum = "0", nNum = "0";
                    if (!string.IsNullOrWhiteSpace(obj["yNum"].ToString()))
                    {
                        yNum = obj["yNum"].ToString();
                        numTotal += double.Parse(yNum);
                        yNumTotal += double.Parse(yNum);
                    }
                    if (!string.IsNullOrWhiteSpace(obj["nNum"].ToString()))
                    {
                        nNum = obj["nNum"].ToString();
                        numTotal += double.Parse(nNum);
                    }
                    yTotal += double.Parse(yNum);
                    nTotal += double.Parse(nNum);
                    bg_sub = new DbPlanBaogongSub();
                    bg_sub.createtime = getNow();
                    bg_sub.createuser = createuser;
                    bg_sub.happenDate = getNowDate();
                    bg_sub.isdel = 0;
                    bg_sub.nNum = nNum;
                    bg_sub.yNum = yNum;
                    bg_sub.isFrom = isFrom;
                    bg_sub.bgCode = bgCode;
                    bg_sub.gxCode = pgTable.Rows[0]["gxCode"].ToString();
                    bg_sub.userCode = obj["userCode"].ToString();
                    oper = new OperateModel();
                    oper.Data = bg_sub;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);

                }
                #endregion

                if (double.Parse(defNumber) != yTotal)
                {
                    rsl.Result = false;
                    rsl.Message = "人员的总合格数与录入的报工总合格数不相等";
                    return rsl;
                }
                if (double.Parse(defnNumber) != nTotal)
                {
                    rsl.Result = false;
                    rsl.Message = "人员的总不合格数与录入的报工总不合格数不相等";
                    return rsl;
                }

                #region 主表
                DbPlanBaogongMain bg_main;
                bg_main = new DbPlanBaogongMain();
                bg_main.bgCode = bgCode;
                bg_main.bgType = "JTBG";
                bg_main.nNum = nTotal.ToString();
                bg_main.yNum = yTotal.ToString();
                bg_main.memo = "机台报工";
                bg_main.happenDate = jsons[0]["happenDate"].ToString();
                bg_main.createtime = getNow();
                bg_main.createuser = createuser;
                bg_main.gxCode = pgTable.Rows[0]["gxCode"].ToString();
                bg_main.pKey = pKey;
                bg_main.plCodes = pgTable.Rows[0]["plCodes"].ToString();
                bg_main.isDel = 0;
                bg_main.isFrom = isFrom;
                if (!string.IsNullOrWhiteSpace(ppid))
                {
                    bg_main.ppId = ppid;
                }
                oper = new OperateModel();
                oper.Data = bg_main;
                oper.Types = OperateModel.OperateType.Add;
                operList.Add(oper);
                #endregion

                string bNum = "1", bnNum = "0", msg = "", bgxCode = "";
                bool gxIsEnd = false;//是否为最后一道工序
                this.CheckBackGxYnum(pKey, ref bNum, ref bnNum, ref msg, ref gxIsEnd, ref bgxCode);
                if (string.IsNullOrWhiteSpace(bNum))
                {
                    rsl.Message = msg;
                    return rsl;
                }
                #endregion

                #region 判断当前工序的下一道工序大类是否允许报工
                var nextParentGx = "";
                getNextGx(ppid, pgTable.Rows[0]["gxCode"].ToString(), ref nextParentGx);
                if (!string.IsNullOrWhiteSpace(nextParentGx))
                {
                    sb.Clear();
                    sb.Append("select * from pi_ProductionPlan_process where 1=1 and ppId='" + ppid + "' and parentCode='" + nextParentGx + "'");
                    sb.Append(" and isnull(canBg,0)<>1 ");
                    var gxtable = cmd.GetDataTable(sb.ToString());  //计划工序表
                    if (gxtable.Rows.Count > 0)
                    {
                        oper = new OperateModel();
                        var planProcess = new DbPlanGongXu();
                        planProcess.ppId = ppid;
                        planProcess.parentCode = nextParentGx;
                        planProcess.canBg = 1;
                        oper = new OperateModel();
                        oper.Data = planProcess;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "ppId,parentCode";
                        operList.Add(oper);
                    }
                }
                #endregion

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }



        //向记录表中插入待入库数据
        public ReturnResult addInKuInfo(string bgCode, string pgCode,string wareCode,string yNum,string createuser, ref List<OperateModel> list)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select proCode,proName,spec,cu_yanse,cu_shangbiao from pi_PlanPaiGong_info pg ");
                sb.Append("inner join V_ProductionPlan_products pro on pro.id =pg.ppId ");
                sb.Append("where pg.isdel=0 and tpCode='" + pgCode + "'");
                var dt = cmd.GetDataTable(sb.ToString());

                // 如果查询不到
                if (dt.Rows.Count == 0)
                {
                    rsl.Result = false;
                    rsl.Message = "查询不到派工单或相关计划信息";
                    return rsl;
                }

                var proCode = dt.Rows[0]["proCode"].ToString();
                var proName = dt.Rows[0]["proName"].ToString();
                var spec = dt.Rows[0]["spec"].ToString();
                var color = dt.Rows[0]["cu_yanse"].ToString();
                var shangbiao = dt.Rows[0]["cu_shangbiao"].ToString();

                var info = new DbRestockInfo
                {
                    bgCode= bgCode,
                    pgCode = pgCode,
                    proCode = proCode,
                    proName = proName,
                    spec = spec,
                    color = color,
                    shangbiao = shangbiao,
                    number = yNum,
                    happenDate = getNowDate(),
                    toUser = createuser,
                    wareCode = wareCode,
                    dataType = "inKuTask",
                    status = "0",
                    createtime = getNow(),
                    createuser = createuser,
                    isdel = "0",
                    rdCode = getTimeString(),
                };

                oper = new OperateModel
                {
                    Data = info,
                    Types = OperateModel.OperateType.Add
                };

                list.Add(oper);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
                rsl.Result = false;
            }

            return rsl;
        }

        // 统计不合格数量
        ReturnResult UnqualifiedInfo(string gxCode, string nNum, string pgCode, string bgCode, string createuser, ref List<OperateModel> list)
        {
            var sumResult = new ReturnResult();
            try
            {
                #region 判断工序是否属于用户自定义的工序大类

                // gxCode = dymzddtm
                // nNum = 2
                // pgCode = TP2023090830
                // createuser = hxd
                // 

                var parentSql_template = @"select parentCode from pi_ProductionPlan_process gx 
left join pi_PlanPaiGong_info pg on gx.ppId = pg.ppId and pg.gxCode=gx.gxCode
where pg.isDel = 0 and tpCode = '{0}' and pg.gxCode ='{1}'";
                var parentSql = string.Format(parentSql_template, pgCode,gxCode);

                var parentDt = cmd.GetDataTable(parentSql);

                var parentCode = "";
                if (parentDt.Rows.Count > 0)
                {
                    parentCode = parentDt.Rows[0]["parentCode"].ToString();
                }

                var config_sql = "select * from sys_parameters_info where parCode = 'rs_ct_config'";
                var config_dt = cmd.GetDataTable(config_sql);

                var configString = config_dt.Rows[0]["parValue"].ToString();
                var rc_config = JsonConvert.DeserializeObject<Rs_Ct_Config>(configString);

                if (!rc_config.gx.Contains(parentCode))
                {
                    // 返回returnResult，添加错误信息, 如果致命报错，连报工也不继续下去了
                    sumResult.Result = true;
                    sumResult.Message = "不需要统计当前报工工序";

                    return sumResult;
                }

                #endregion 判断工序是否属于用户自定义的工序大类

                // 查询生产订单子表信息
                // 把*改成具体字段，应该查生产计划products视图，如果没有spec，加上
                // 自动任务中把spec,proname等加上
                var sql_template = @"select * from pi_PlanPaiGong_info pg inner join 
                        pi_ProductionPlan_products pro on pro.id =pg.ppId inner join 
    fun_Inventory_Info inv on pro.proCode = inv.proCode
where pg.isdel=0 and tpCode='{0}'";
                var sql = string.Format(sql_template, pgCode);
                var dt = cmd.GetDataTable(sql);

                // 如果查询不到
                if (dt.Rows.Count == 0)
                {
                    sumResult.Result = false;
                    sumResult.Message = "查询不到生产订单子表信息";
                    return sumResult;
                }

                var dr = dt.Rows[0];

                var proCode = dr["proCode"].ToString();
                var proName = dr["proName"].ToString();
                var spec = dr["spec"].ToString();
                var color = dr["cu_yanse"].ToString();
                var shangbiao = dr["cu_shangbiao"].ToString();

                var info = new DbRestockInfo
                {
                    bgCode = bgCode,
                    pgCode = pgCode,
                    proCode = proCode,
                    proName = proName,
                    spec = spec,
                    color = color,
                    shangbiao = shangbiao,
                    number = nNum,
                    //happenDate = DateTime.Now.ToString("yyyy-MM-dd"),
                    happenDate = getNowDate(),
                    toUser = createuser,
                    status = "0",
                    createtime = getNow(),
                    createuser = createuser,
                    isdel = "0",
                    rdCode = getTimeString(),
                    dataType = "restock"
                };

                oper = new OperateModel
                {
                    Data = info,
                    Types = OperateModel.OperateType.Add
                };

                list.Add(oper);
            }
            catch (Exception ex)
            {
                sumResult.Message = ex.Message;
                return sumResult;
            }

            sumResult.Result = true;
            sumResult.Message = "不合格报工统计成功";

            return sumResult;
        }

        //// 汇总不合格并进行补货改标流程
        //public void Summary_Restock_ChangeTag()
        //{
        //    var sql = "select * from sys_parameters_info where parCode = 'rs_ct_config'";
        //    var dt = cmd.GetDataTable(sql);

        //    var configString = dt.Rows[0]["parValue"].ToString();
        //    var rc_config = JsonConvert.DeserializeObject<Rs_Ct_Config>(configString);

        //    // 需要检查现存量的仓库
        //    var houseString = "'";
        //    foreach (var house in rc_config.restock.outWarehouse)
        //    {
        //        houseString += house;
        //        houseString += "',";
        //    }
        //    houseString = houseString.TrimEnd(',');

        //    CuDbHelper cuDb = new CuDbHelper();

        //    // 每次统计，需要生成调拨任务的列表
        //    var restockList = new List<Restock_Keyword>();
        //    // 每次统计，需要生成改标任务的列表
        //    var changeTagList = new List<Restock_Keyword>();

        //    // 查找不合格数据，按照存货编码、规格、颜色、商标汇总

        //    var sumSql = "select * from pi_restock_info where status = '0' and isdel = 0 ";
        //    var sumDt = cmd.GetDataTable(sumSql);

        //    var groupedData = sumDt.AsEnumerable().GroupBy(r => new
        //    {
        //        proCode = r.Field<string>("proCode"),
        //        spec = r.Field<string>("spec"),
        //        color = r.Field<string>("color"),
        //        shangbiao = r.Field<string>("shangbiao"),
        //    });

        //    // 对于每组数据
        //    foreach (var data in groupedData)
        //    {
        //        var theKey = data.Key;
        //        var proCode = theKey.proCode;
        //        var color = theKey.color;
        //        var shangbiao = theKey.shangbiao;
        //        var proName = data.First()["proName"].ToString();
        //        var spec = data.First()["spec"].ToString();

        //        // 数量求和
        //        var nSum = data.Sum(r => decimal.Parse(r["number"].ToString()));

        //        // 查询现存量表 CurrentStock
        //        // 把每个仓库的数量，都记录下来
        //        // 先不做，先默认一个仓库
        //        var stockSql_template = @"select * from CurrentStock where cInvCode = '{0}' 
        //                                  and cFree1 = '{1}' and cFree3 = '{2}' and cWhCode in ({3})";
        //        var stockSql = string.Format(stockSql_template, proCode, color, shangbiao, houseString);
        //        var stockDt = cuDb.getData(stockSql, "");

        //        var stockNum = 0.0m;

        //        // 也得加tableRow的判断
        //        if (stockDt.Rows.Count > 0)
        //        {
        //            stockNum = decimal.Parse(stockDt.Rows[0]["iquantity"].ToString());
        //        }

        //        // 如果现存量大于不合格汇总数量
        //        // 向任务中心插入出库信息
        //        if (stockNum >= nSum)
        //        {
        //            restockList.Add(new Restock_Keyword
        //            {
        //                proName = proName,
        //                spec = spec,
        //                color = color,
        //                proCode = proCode,
        //                shangbiao = shangbiao,
        //                number = nSum.ToString()
        //            });
        //        }
        //        // 生成改标申请单
        //        else
        //        {
        //            // 如果现存量不为零
        //            if (stockNum != 0.0m)
        //            {
        //                //将现存量生成出库任务
        //                restockList.Add(new Restock_Keyword
        //                {
        //                    proName = proName,
        //                    spec = spec,
        //                    color = color,
        //                    proCode = proCode,
        //                    shangbiao = shangbiao,
        //                    number = stockNum.ToString()
        //                });

        //                //剩余数量 = 不合格数量-现存数量
        //                var remainNum = nSum - stockNum;

        //                //剩余数量 生成改标任务
        //                changeTagList.Add(new Restock_Keyword
        //                {
        //                    proName = proName,
        //                    spec = spec,
        //                    color = color,
        //                    proCode = proCode,
        //                    shangbiao = shangbiao,
        //                    number = remainNum.ToString()
        //                });
        //            }
        //            // 不合格数量全部生成改标任务
        //            else
        //            {
        //                changeTagList.Add(new Restock_Keyword
        //                {
        //                    proName = proName,
        //                    spec = spec,
        //                    color = color,
        //                    proCode = proCode,
        //                    shangbiao = shangbiao,
        //                    number = nSum.ToString()
        //                });
        //            }
        //        }
        //    }

        //    operList = new List<OperateModel>();
        //    var taskCode = getTimeString();

        //    // 处理补货列表
        //    if (restockList.Count > 0)
        //    {
        //        var restockJson = JsonConvert.SerializeObject(restockList);
        //        var restockTask = new DbTaskCenter
        //        {
        //            id = taskCode,
        //            businessType = "restock",
        //            businessId = DateTime.Now.ToString("yyyy-MM-dd"),
        //            toUser = rc_config.restock.toUser,
        //            contents = restockJson,
        //            createtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
        //            isFinish = 0,
        //            taskCode = taskCode,
        //            memo = "自动统计不合格报工中的补货信息",
        //        };

        //        oper = new OperateModel
        //        {
        //            Types = OperateModel.OperateType.Add,
        //            Data = restockTask
        //        };
        //        operList.Add(oper);
        //    }


        //    // 处理改标列表
        //    if (changeTagList.Count > 0)
        //    {
        //        var changeTagJson = JsonConvert.SerializeObject(changeTagList);
        //        var changeTagTask = new DbTaskCenter
        //        {
        //            id = taskCode,
        //            businessType = "changeTag",
        //            businessId = DateTime.Now.ToString("yyyy-MM-dd"),
        //            toUser = rc_config.changeTag.toUser,
        //            contents = changeTagJson,
        //            createtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
        //            isFinish = 0,
        //            taskCode = taskCode,
        //            memo = "自动统计不合格报工中的改标信息",
        //        };

        //        oper = new OperateModel
        //        {
        //            Types = OperateModel.OperateType.Add,
        //            Data = changeTagTask
        //        };
        //        operList.Add(oper);
        //    }

        //    // 对处理过的数据，做标记
        //    foreach (DataRow row in sumDt.Rows)
        //    {
        //        var changed = new DbRestockInfo
        //        {
        //            id = int.Parse(row["id"].ToString()),
        //            status = "1"
        //        };

        //        oper = new OperateModel { Conditions = "id", Data = changed, Types = OperateModel.OperateType.Edit };
        //        operList.Add(oper);
        //    }

        //    // 执行
        //    if (operList.Count > 0)
        //    {
        //        try
        //        {
        //            var result = cmd.MoreUpdate(operList);
        //        }
        //        catch (Exception ex)
        //        {
        //            var c = ex.Message;
        //        }

        //    }
        //}

        /// <summary>
        /// 自动修改分配未除尽的数据，使其变为临近的整数
        /// </summary>
        /// <param name="jsons"></param>
        /// <param name="temcY"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private ReturnResult updateNum(List<JObject> jsons, double temcY, string type)
        {
            rsl = new ReturnResult();
            var baseNum = 0.01;//平分的基数
            var temNum = temcY;
            if (temcY == 0)
            {
                rsl.Result = true;
                return rsl;
            }
            if (temcY < 0)
            {
                temNum = -temcY;
            }
            var tNum = temNum / baseNum;
            if (tNum.ToString().IndexOf('.') > -1)
            {
                if (type.Equals("yNum"))
                {
                    rsl.Message = "合格数未除尽";
                }
                else if (type.Equals("nNum"))
                {
                    rsl.Message = "不合格数未除尽";
                }
                return rsl;
            }
            if (tNum > jsons.Count)
            {
                rsl.Message = "多余的小数分配人数大于报工的人数";
                return rsl;
            }
            if (temcY < 0)
            {
                baseNum = -baseNum;
            }
            for (int i = 0; i < tNum; i++)
            {
                var json = jsons[i];
                if (type.Equals("yNum"))
                {
                    json["yNum"] = (double.Parse(json["yNum"].ToString()) + baseNum).ToString();
                }
                else if (type.Equals("nNum"))
                {
                    json["nNum"] = (double.Parse(json["nNum"].ToString()) + baseNum).ToString();
                }
            }
            rsl.Result = true;
            return rsl;
        }
        /// <summary>
        /// 修改生产计划的完成状态
        /// gxIsEnd 是否最后一道工序
        /// </summary>
        private void ChanagePlanStatus(bool gxIsEnd, Dictionary<string, object> dic, ref List<OperateModel> operList,bool onlyY)
        {
            StringBuilder sb = new StringBuilder();
            var ppid = dic["ppid"].ToString();
            var parentGx = dic["parentGx"].ToString();
            var yTotal = (double)dic["yTotal"];
            var nTotal = (double)dic["nTotal"];
            var plNumber = (double)dic["plNumber"];
            var nBgCode = "";//不需要统计的报工单号
            if (dic.ContainsKey("nBgCode"))
            {
                nBgCode = dic["nBgCode"].ToString();
            }
            #region 判定对应的生产计划是否完工
            if (gxIsEnd)
            {
                #region 查询该计划中最后一道工序的所有报工记录
                sb.Clear();
                sb.Append("select isnull(sum(convert(decimal(18,2),yNum)),0) yNum,isnull(sum(convert(decimal(18,2),nNum)),0) nNum  ");
                sb.Append(" from pi_PlanBaogong_main where 1=1 and isDel<>1 ");
                sb.Append(" and ppId ='" + ppid + "' and gxCode in(select gxCode ");
                sb.Append(" from pi_ProductionPlan_process where 1=1 and ppId='" + ppid + "' and parentCode='" + parentGx + "') ");
                if (!string.IsNullOrWhiteSpace(nBgCode))
                {
                    sb.Append(" and bgCode<>'" + nBgCode + "'");
                }
                var gxBgNumDt = cmd.GetDataTable(sb.ToString());
                var totalNum = 0.0;
                if (gxBgNumDt != null && gxBgNumDt.Rows.Count > 0)
                {
                    if (onlyY)
                    {
                        foreach (DataRow row in gxBgNumDt.Rows)
                        {
                            totalNum += ( Convert.ToDouble(row["yNum"].ToString()) ); //最后一道工序所有已报工合格数
                        }
                    }
                    else
                    {
                        foreach (DataRow row in gxBgNumDt.Rows)
                        {
                            totalNum += (Convert.ToDouble(row["yNum"].ToString()) + Convert.ToDouble(row["nNum"].ToString())); //最后一道工序所有已报工数
                        }
                    }
                    
                }
                if (onlyY)
                    totalNum += yTotal ;//加上本次报工的记录
                else
                    totalNum += yTotal + nTotal;//加上本次报工的记录

                if (totalNum >= plNumber)
                {
                    var product = new DbProductionPlanPro();
                    product.id = int.Parse(ppid);
                    product.status = "ps-finish";
                    oper = new OperateModel();
                    oper.Data = product;
                    oper.Conditions = "id";
                    oper.Types = OperateModel.OperateType.Edit;
                    operList.Add(oper);
                }
                #endregion
            }
            #endregion
        }
        /// <summary>
        /// 获取上道工序的合格数(通过报工获取)
        /// </summary>
        /// <param name="pKey"></param>
        /// <param name="quaNum"></param>
        /// <param name="msg"></param>
        public void CheckBackGxYnum(string pKey, ref string quaNum, ref string bhgNum, ref string msg, ref bool gxIsEnd, ref string b_gxCode)
        {
            StringBuilder sb = new StringBuilder();
            quaNum = "0";
            bhgNum = "0";
            sb.Append("select isnull(pro.plCode,'') plCodes,pg.number,pg.ppId from pi_PlanPaiGong_info pg  ");//
            sb.Append("inner join pi_ProductionPlan_products pro on pro.id =pg.ppId where tpCode='" + pKey + "'");//
            var pgTable = cmd.GetDataTable(sb.ToString());

            sb.Clear();
            sb.Append("select top 1 gxCode from fun_GxPrice_info where isdel=0 and cgxCode ");
            sb.Append(" in( select gxCode from pi_PlanPaiGong_info where tpCode='" + pKey + "')");
            var cgxTable = cmd.GetDataTable(sb.ToString());
            DataTable fgxTable = new DataTable();
            bool IsSingle = true;
            if (!string.IsNullOrWhiteSpace(pgTable.Rows[0]["plCodes"].ToString()))
            {
                #region 单计划
                sb.Clear();
                sb.Append("select cCode,orderNum from fun_CommonData_Info");
                sb.Append(" where cType='GX' and isdel=0 and status='Y' and ");
                sb.Append(" cCode in(select case isChild when '0' then gxCode when '1' then parentCode end as gxCode ");
                //sb.Append("from pi_ProductionPlan_process where plCode='" + pgTable.Rows[0]["plCodes"].ToString() + "' )");
                sb.Append("from pi_ProductionPlan_process where ppId='" + pgTable.Rows[0]["ppId"].ToString() + "' )");
                sb.Append(" order by orderNum asc");
                fgxTable = cmd.GetDataTable(sb.ToString());
                #endregion
                //}
            }


            if (cgxTable.Rows.Count < 1)
            {
                msg = "工序信息错误";
                return;
            }

            //string b_gxCode = "";//上一道工序编码
            for (int i = 0; i < fgxTable.Rows.Count; i++)
            {
                if (cgxTable.Rows[0][0].ToString() == fgxTable.Rows[i]["cCode"].ToString())
                {
                    #region 判断该工序是否为最后一道工序
                    if (i == (fgxTable.Rows.Count - 1))
                    {
                        gxIsEnd = true;
                    }
                    #endregion
                    if (i < 1)
                    {
                        b_gxCode = fgxTable.Rows[i]["cCode"].ToString();
                        //quaNum = "99999999";
                        quaNum = pgTable.Rows[0]["number"].ToString();
                        return;
                    }
                    else
                    {
                        b_gxCode = fgxTable.Rows[i - 1]["cCode"].ToString();
                    }
                    break;
                }
            }
            if (string.IsNullOrWhiteSpace(b_gxCode))
            {
                msg = "前置工序数据获取失败";
                return;
            }
            if (IsSingle)
            {
                sb.Clear();
                sb.Append("select sum(CONVERT(decimal(18,2),yNum)) yNum,sum(CONVERT(decimal(18,2),nNum)) nNum from pi_PlanBaogong_main where ");
                sb.Append("gxCode in(select cgxCode from fun_GxPrice_info where ");
                //sb.Append("gxCode='" + b_gxCode + "' and isdel=0) and plCodes='");
                //sb.Append(pgTable.Rows[0]["plCodes"].ToString() + "' and isDel=0 ");
                sb.Append("gxCode='" + b_gxCode + "' and isdel=0) and ppId='" + pgTable.Rows[0]["ppId"].ToString() + "'");
                sb.Append(" and isDel=0 ");
                var numTable = cmd.GetDataTable(sb.ToString());
                if (numTable.Rows.Count > 0)
                {
                    if (numTable.Rows[0]["yNum"] != null && !string.IsNullOrWhiteSpace(numTable.Rows[0]["yNum"].ToString()))
                    {
                        quaNum = numTable.Rows[0]["yNum"].ToString();
                    }
                    if (numTable.Rows[0]["nNum"] != null && !string.IsNullOrWhiteSpace(numTable.Rows[0]["nNum"].ToString()))
                    {
                        bhgNum = numTable.Rows[0]["nNum"].ToString();
                    }
                }
            }

        }
        /// <summary>
        /// 获取班组派工数量
        /// </summary>
        /// <param name="groupCode">班组编码</param>
        /// <param name="pgDate">派工日期</param>
        /// <returns></returns>
        public ReturnResult PaiNumberByGroup(string groupCode, string pgDate)
        {
            rsl = new ReturnResult();
            try
            {
                //查班组的派工数量
                StringBuilder sb = new StringBuilder();
                sb.Append("select sum(CONVERT(decimal(18,2),number)) number,sDate,groupCode,pKey ");
                sb.Append("from pi_PaiGong_main where  groupCode='" + groupCode + "' and isdel=0 and isFinish=0");
                sb.Append("group by sDate,groupCode,pKey order by sDate asc");
                var table = cmd.GetDataTable(sb.ToString());
                List<string> nameList = new List<string>();//x
                List<string> dataList = new List<string>();//y
                Dictionary<string, object> d;
                List<double> wcs = new List<double>();//完成数
                List<double> wwc = new List<double>();//未完成数
                foreach (DataRow r in table.Rows)
                {

                    sb.Clear();
                    sb.Append("select SUM(CONVERT(decimal(18,2),yNum)) yNum from pi_PlanBaogong_main where isDel=0 ");
                    sb.Append(" and pKey = '" + r["pKey"].ToString() + "' ");
                    var bgTable = cmd.GetDataTable(sb.ToString());

                    double wc = 0;
                    if (bgTable.Rows[0][0] != null && !string.IsNullOrWhiteSpace(bgTable.Rows[0][0].ToString()))
                    {
                        wc = double.Parse(bgTable.Rows[0][0].ToString());
                    }
                    double nwc = double.Parse(r["number"].ToString()) - wc;
                    wcs.Add(wc); wwc.Add(nwc);

                    nameList.Add(r["sDate"].ToString());

                }
                List<Dictionary<string, object>> dList = new List<Dictionary<string, object>>();
                d = new Dictionary<string, object>();
                d["name"] = "已完成数";
                d["type"] = "bar";
                d["stack"] = "total";
                var cd = new Dictionary<string, object>();
                cd["show"] = true;
                d["label"] = cd;
                d["data"] = wcs;
                dList.Add(d);
                d = new Dictionary<string, object>();
                d["name"] = "未完成数";
                d["type"] = "bar";
                d["stack"] = "total";
                cd = new Dictionary<string, object>();
                cd["show"] = true;
                d["label"] = cd;
                d["data"] = wwc;
                dList.Add(d);
                d = new Dictionary<string, object>();
                if (nameList.Count < 1)
                    nameList.Add(DateTime.Now.ToString("yyyy-MM-dd"));
                d["names"] = nameList;
                d["datas"] = dList;
                #region   获取班组在生产日期排的序号  orNum
                sb.Clear();
                sb.Append("select orNum from pi_PaiGong_main where groupCode = '" + groupCode + "' ");
                sb.Append(" and sDate = '" + pgDate + "' order by orNum desc ");
                var numTable = cmd.GetDataTable(sb.ToString());
                int orNum = 1;
                if (numTable.Rows.Count > 0)
                    orNum = Convert.ToInt32(numTable.Rows[0][0].ToString()) + 1;

                d["orNum"] = orNum;
                #endregion
                rsl.Result = true;
                rsl.Data = d;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 根据编码获取报工明细
        /// </summary>
        /// <param name="condition">编码</param>
        /// <returns></returns>
        public ReturnResult GetBaoGongDetail(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select distinct s.*,ug.userName from pi_PlanBaogong_sub s");//,ug.groupCode,ug.groupName
                sb.Append(" left join V_Users_Group ug on s.userCode=ug.userCode ");
                sb.Append(" where s.isdel=0 ");
                sb = CreateSelectCondition(sb, condition);
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 报工记录删除
        /// </summary>
        /// <param name="keyCode">关键编码</param>
        /// <param name="isMain">是否是主信息</param>
        /// <returns></returns>
        public ReturnResult DelBaoGongInfo(string keyCodes, string isMain, Dictionary<string, Object> pars = null)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                DbPlanBaogongMain m;
                DbPlanBaogongSub s;
                DbemployeeWage w;
                DbRestockInfo r;
                StringBuilder sb = new StringBuilder();
                DataTable mTable = new DataTable();
                string number = "0", nNum = "0", pKey = "", ppId = "";
                string usCode = "";
                #region  通过来源（pc/app）获取删除人员
                if (pars != null)
                {
                    if (pars.ContainsKey("userCode") && !string.IsNullOrWhiteSpace(pars["userCode"].ToString()))
                    {
                        usCode = pars["userCode"].ToString();
                    }
                    else
                    {
                        rsl.Message = "参数错误：缺少删除人员信息";
                        return rsl;
                    }
                }
                else
                {
                    usCode = userLogin.UserInfo().userCode;
                }
                #endregion
                var arr = keyCodes.Split(',');
                var ppidDic = new Dictionary<string, string>();

                #region
                if (bool.Parse(isMain))
                {
                    foreach (var keyCode in arr)
                    {
                        if (string.IsNullOrWhiteSpace(keyCode))
                        {
                            continue;
                        }

                        #region 如果报工记录相关的记录包含已汇总到自动任务中的，不允许删除报工记录
                        sb.Clear();
                        sb.Append("select * from pi_restock_info where status <>'0' and isdel=0 and bgCode ='" + keyCode + "'");
                        var rtable = cmd.GetDataTable(sb.ToString());
                        if (rtable.Rows.Count > 0)
                        {
                            rsl.Message = "当前报工记录已生成相关的任务，</br>暂不支持删除报工记录。";
                            return rsl;
                        }
                        #endregion

                        sb.Clear();
                        sb.Append("select * from pi_PlanBaogong_main where bgCode='" + keyCode + "'");
                        sb.Append(" and isdel=0");
                        mTable = cmd.GetDataTable(sb.ToString());
                        number = mTable.Rows[0]["yNum"].ToString();
                        nNum = mTable.Rows[0]["nNum"].ToString();

                        #region 只允许删除当日报工记录
                        if (mTable.Rows[0]["happenDate"].ToString()!=getNowDate())
                        {
                            rsl.Message = "只允许删除当日报工记录";
                            return rsl;
                        }
                        #endregion

                        #region 如果报工记录相关的计划有退料记录，不让删除报工记录
                        ppId = mTable.Rows[0]["ppId"].ToString();
                        sb.Clear();
                        sb.Append("select * from pi_PaiGong_material_main where status = 'bl-in' and plCode like '%" + ppId + "%'");
                        var tltable = cmd.GetDataTable(sb.ToString());
                        if (tltable.Rows.Count > 0)
                        {
                            rsl.Message = "当前报工记录相关的计划已将次品退回，</br>暂不支持删除报工记录。";
                            return rsl;
                        }
                        #endregion

                        #region 根据报工编码删除全部报工及相关信息

                        #region 主表信息
                        m = new DbPlanBaogongMain();
                        m.bgCode = keyCode;
                        m.isDel = 1;
                        m.delDate = getNow();
                        m.delUser = usCode;
                        oper = new OperateModel();
                        oper.Data = m;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "bgCode";
                        operList.Add(oper);
                        #endregion

                        #region 子表数据
                        s = new DbPlanBaogongSub();
                        s.bgCode = keyCode;
                        s.isdel = 1;
                        s.delDate = getNow();
                        s.delUser = usCode;
                        oper = new OperateModel();
                        oper.Data = s;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "bgCode";
                        operList.Add(oper);
                        #endregion

                        #region 关联员工绩效
                        w = new DbemployeeWage();
                        w.bgCode = keyCode;
                        w.isdel = 1;
                        w.delDate = getNow();
                        w.delUser = usCode;
                        oper = new OperateModel();
                        oper.Data = w;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "bgCode";
                        operList.Add(oper);
                        #endregion

                        #region 改标、补货、入库（未汇总到自动任务）记录
                        r = new DbRestockInfo();
                        r.bgCode = keyCode;
                        r.isdel = "1";
                        r.deltime = getNow();
                        r.deluser = usCode;
                        oper = new OperateModel();
                        oper.Data = r;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "bgCode";
                        operList.Add(oper);
                        #endregion

                        #endregion
                        //派工单号
                        pKey = mTable.Rows[0]["pKey"].ToString();
                        //报工的工序
                        var gxCode = mTable.Rows[0]["gxCode"].ToString();
                        var idKeyGx = ppId + "," + pKey + "," + gxCode;
                        var value = number + "," + nNum;
                        if (!ppidDic.ContainsKey(idKeyGx))
                        {
                            ppidDic.Add(idKeyGx, value);
                        }
                        else
                        {
                            var arrN = ppidDic[idKeyGx].Split(',');
                            var temYNum = (Convert.ToDouble(arrN[0]) + Convert.ToDouble(number)).ToString();//合格数
                            var temNNum = (Convert.ToDouble(arrN[1]) + Convert.ToDouble(nNum)).ToString();//不合格数
                            value = temYNum + "," + temNNum;
                            ppidDic[idKeyGx] = value;
                        }
                    }
                }
                else
                {
                    var bgCode = "";
                    var cyNum = 0.0;
                    var cnNum = 0.0;
                    foreach (var keyCode in arr)
                    {
                        if (string.IsNullOrWhiteSpace(keyCode))
                        {
                            continue;
                        }

                        #region 如果报工记录相关的记录包含已汇总到自动任务中的，不允许删除报工记录
                        sb.Clear();
                        sb.Append("select * from pi_restock_info where status <>'0' and isdel=0 and bgCode in(");
                        sb.Append(" select bgCode from pi_PlanBaogong_sub where id=" + keyCode + ")");
                        var rtable = cmd.GetDataTable(sb.ToString());
                        if (rtable.Rows.Count > 0)
                        {
                            rsl.Message = "当前报工记录已生成相关的任务，</br>暂不支持删除报工记录。";
                            return rsl;
                        }
                        #endregion

                        #region 根据报工明细id删除指定报工信息（子表）及绩效
                        sb.Clear();
                        sb.Append("select bg.* ,p.isNeedIn from pi_PlanBaogong_main bg ");
                        sb.Append("inner join pi_PlanPaiGong_info p on p.tpCode=bg.pKey where bgCode in(");
                        sb.Append(" select bgCode from pi_PlanBaogong_sub where id=" + keyCode + ")");
                        mTable = cmd.GetDataTable(sb.ToString());

                        #region 只允许删除当日报工记录
                        if (mTable.Rows[0]["happenDate"].ToString() != getNowDate())
                        {
                            rsl.Message = "只允许删除当日报工记录";
                            return rsl;
                        }
                        #endregion

                        #region 如果报工记录相关的计划有退料记录，不让删除报工记录
                        ppId = mTable.Rows[0]["ppId"].ToString();
                        bgCode = mTable.Rows[0]["bgCode"].ToString();
                        sb.Clear();
                        sb.Append("select * from pi_PaiGong_material_main where status = 'bl-in' and plCode like '%" + ppId + "%'");
                        var tltable = cmd.GetDataTable(sb.ToString());
                        if (tltable.Rows.Count > 0)
                        {
                            rsl.Message = "当前报工记录相关的计划已将次品退回，</br>暂不支持删除报工记录。";
                            return rsl;
                        }
                        #endregion

                        sb.Clear();
                        sb.Append("select * from pi_PlanBaogong_sub where id=" + keyCode);
                        var sTable = cmd.GetDataTable(sb.ToString());
                        cyNum += double.Parse(sTable.Rows[0]["yNum"].ToString());
                        cnNum += double.Parse(sTable.Rows[0]["nNum"].ToString());
                        number = sTable.Rows[0]["yNum"].ToString();
                        nNum = sTable.Rows[0]["nNum"].ToString();

                        #region 子表数据
                        s = new DbPlanBaogongSub();
                        s.id = int.Parse(keyCode);
                        s.isdel = 1;
                        s.delDate = getNow();
                        s.delUser = usCode;
                        oper = new OperateModel();
                        oper.Data = s;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "id";
                        operList.Add(oper);
                        #endregion

                        #region 关联员工绩效
                        w = new DbemployeeWage();
                        w.bgCode = mTable.Rows[0]["bgCode"].ToString();
                        w.userCode = sTable.Rows[0]["userCode"].ToString();
                        w.isdel = 1;
                        w.delDate = getNow();
                        w.delUser = usCode;
                        oper = new OperateModel();
                        oper.Data = w;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "bgCode,userCode";
                        operList.Add(oper);
                        #endregion
                        #endregion
                        //派工单号
                        pKey = mTable.Rows[0]["pKey"].ToString();
                        //报工的工序
                        var gxCode = mTable.Rows[0]["gxCode"].ToString();
                        var idKeyGx = ppId + "," + pKey + "," + gxCode;
                        var value = number + "," + nNum;
                        if (!ppidDic.ContainsKey(idKeyGx))
                        {
                            ppidDic.Add(idKeyGx, value);
                        }
                        else
                        {
                            var arrN = ppidDic[idKeyGx].Split(',');
                            var temYNum = (Convert.ToDouble(arrN[0]) + Convert.ToDouble(number)).ToString();//合格数
                            var temNNum = (Convert.ToDouble(arrN[1]) + Convert.ToDouble(nNum)).ToString();//不合格数
                            value = temYNum + "," + temNNum;
                            ppidDic[idKeyGx] = value;
                        }
                    }
                    #region 主表信息
                    m = new DbPlanBaogongMain();
                    m.bgCode = bgCode;
                    m.yNum = (double.Parse(mTable.Rows[0]["yNum"].ToString()) - cyNum).ToString();
                    m.nNum = (double.Parse(mTable.Rows[0]["nNum"].ToString()) - cnNum).ToString();
                    number = m.yNum;
                    nNum = m.nNum;
                    if (double.Parse(m.nNum) < 1 && double.Parse(m.yNum) < 1)
                    {
                        m.isDel = 1;
                        m.delDate = getNow();
                        m.delUser = usCode;
                    }
                    oper = new OperateModel();
                    oper.Data = m;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "bgCode";
                    operList.Add(oper);
                    #endregion

                    #region 补货改标记录
                    if (double.Parse(mTable.Rows[0]["nNum"].ToString()) > 0)
                    {
                        r = new DbRestockInfo();
                        r.bgCode = bgCode;
                        r.dataType = "restock";
                        var newnNum = (double.Parse(mTable.Rows[0]["nNum"].ToString()) - cnNum);//删除后的总不合格数
                        if (newnNum > 0)//剩余的不合格数>0 修改数量就行
                        {
                            r.number = newnNum.ToString();
                        }
                        else
                        {//剩余的不合格<=0 软删除
                            r.isdel = "1";
                            r.deltime = getNow();
                            r.deluser = usCode;
                        }
                        oper = new OperateModel();
                        oper.Data = r;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "bgCode,dataType";
                        operList.Add(oper);
                    }
                    #endregion

                    #region 入库记录
                    if (mTable.Rows[0]["isNeedIn"].ToString().Equals("1"))
                    {
                        r = new DbRestockInfo();
                        r.bgCode = bgCode;
                        r.dataType = "inKuTask";
                        var newyNum = (double.Parse(mTable.Rows[0]["yNum"].ToString()) - cyNum);
                        if (newyNum > 0)//剩余的合格数>0 修改数量就行
                        {
                            r.number = newyNum.ToString();
                        }
                        else
                        {//剩余的合格<=0 软删除
                            r.isdel = "1";
                            r.deltime = getNow();
                            r.deluser = usCode;
                        }
                        oper = new OperateModel();
                        oper.Data = r;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "bgCode,dataType";
                        operList.Add(oper);
                    }
                    #endregion

                }
                #endregion

                //每一个计划子表中要删除的工序的工序大类，以及对应的下一道工序大类
                var parentGxDic = new Dictionary<string, object>();
                //最后一道工序
                var endGxDic = new Dictionary<string, object>();

                #region 补货改标配置参数
                sb.Clear();
                sb.Append("select parValue from sys_parameters_info where parCode = 'rs_ct_config'");
                var dt = cmd.GetDataTable(sb.ToString());
                if (dt.Rows.Count < 0)
                {
                    rsl.Message = "缺少补货改标配置参数";
                    return rsl;
                }
                var configString = dt.Rows[0]["parValue"].ToString();
                var rc_config = JsonConvert.DeserializeObject<Rs_Ct_Config>(configString);

                var checkGXs = "";
                foreach (var gxs in rc_config.gx)
                {
                    checkGXs += "'" + gxs + "',";
                }
                checkGXs = checkGXs.TrimEnd(',');//涉及到补货改标的工序

                #endregion

                #region 派工单状态
                if (ppidDic != null && ppidDic.Count > 0)
                {
                    foreach (var key in ppidDic.Keys)
                    {
                        var teArr = key.Split(',');
                        var ppid = teArr[0];//计划单子表id
                        pKey = teArr[1]; //派工单号
                        var gxCode = teArr[2]; //工序编码
                        var valueNum = ppidDic[key].Split(',');
                        number = valueNum[0];//合格数
                        nNum = valueNum[1];//不合格数
                        var parentGx = "";//工序父类型
                        sb.Clear();
                        sb.Append("select * from pi_PlanPaiGong_info where tpCode='" + pKey + "'");
                        var pgTable = cmd.GetDataTable(sb.ToString());
                        sb.Clear();
                        sb.Append("select * from pi_ProductionPlan_process where 1=1 and ppId='" + ppid + "'");
                        sb.Append(" and gxCode='" + gxCode + "'");
                        var gxtable = cmd.GetDataTable(sb.ToString());
                        if (gxtable != null && gxtable.Rows.Count > 0)
                        {
                            parentGx = gxtable.Rows[0]["parentCode"].ToString();
                            var nextParentGx = "";
                            getNextGx(ppid, pgTable.Rows[0]["gxCode"].ToString(), ref nextParentGx);
                            var ppidParGx = ppid + "," + parentGx;
                            if (!parentGxDic.ContainsKey(ppidParGx))
                            {
                                var temDic = new Dictionary<string, string>();
                                temDic["nextParentGx"] = nextParentGx;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               temDic["number"] = number;
                                temDic["nNum"] = nNum;
                                parentGxDic.Add(ppidParGx, temDic);
                            }
                            else
                            {
                                var temDic = (Dictionary<string, string>)parentGxDic[ppidParGx];
                                temDic["number"] = (Convert.ToDecimal(temDic["number"].ToString()) + Convert.ToDecimal(number)).ToString("F2");
                                temDic["nNum"] = (Convert.ToDecimal(temDic["nNum"].ToString()) + Convert.ToDecimal(nNum)).ToString("F2"); ;
                                parentGxDic[ppidParGx] = temDic;
                            }
                        }
                        sb.Clear();
                        sb.Append("select isnull(sum(convert(decimal(18,2),yNum)),'0') yNum,isnull(sum(convert(decimal(18,2),nNum)),'0') nNum from pi_PlanBaogong_main");
                        sb.Append(" where pKey='" + pKey + "' and isdel=0");
                        var nTable = cmd.GetDataTable(sb.ToString());
                        double bgNum = 0,totalYNum=0;
                        if (nTable.Rows.Count > 0)
                        {
                            bgNum = double.Parse(nTable.Rows[0]["yNum"].ToString()) + double.Parse(nTable.Rows[0]["nNum"].ToString());
                            totalYNum = double.Parse(nTable.Rows[0]["yNum"].ToString());
                        }
                        
                        //如果删除的工序是补货改标相关的工序，看合格数与派工数关系判断派工单是否是完成状态
                        double newNum = 0; //剩余报工数
                        if (checkGXs.Contains(parentGx))
                        {
                            newNum = totalYNum - double.Parse(number);//totalYNum 删除前总报工合格数
                        }
                        else
                        {
                            newNum = bgNum - double.Parse(number) - double.Parse(nNum);//bgNum 删除前总的报工数(合格+不合格)   number 删行的合格数 nNum 删行的不合格数
                        }

                        if (double.Parse(pgTable.Rows[0]["number"].ToString()) > newNum)  //派工数>剩余报工数
                        {
                            DbPlanPaiGong pg = new DbPlanPaiGong();
                            pg.tpCode = pKey;
                            pg.isFinish = 0;
                            pg.finishtime = "-";
                            oper = new OperateModel();
                            oper.Data = pg;
                            oper.Types = OperateModel.OperateType.Edit;
                            oper.Conditions = "tpCode";
                            operList.Add(oper);

                            if (gxtable.Rows.Count > 0)
                            {
                                parentGx = gxtable.Rows[0]["parentCode"].ToString();
                                var pgx = new DbPlanGongXu();
                                pgx.id = int.Parse(gxtable.Rows[0]["id"].ToString());
                                pgx.status = "ps-doing";
                                oper = new OperateModel();
                                oper.Data = pgx;
                                oper.Conditions = "id";
                                oper.Types = OperateModel.OperateType.Edit;
                                operList.Add(oper);
                            }
                            else
                            {
                                rsl.Message = "数据错误，找不到派工单对应的工艺";
                                return rsl;
                            }
                        }


                        #region 是否为最后一道工序大类
                        var gxIsEnd = false;
                        //包装计划不按照是否报工完成来判定计划是否完成 （旧）
                        //包装计划如果未勾选是否包装，则报完工计划就完成，不需要打码 （新）
                        sb.Clear();
                        sb.Append("select * from V_ProductionPlan_products where 1=1 and id=" + ppid );  //+ "  and plType<>'P-Pack' "
                        var plDt = cmd.GetDataTable(sb.ToString());
                        if (plDt != null && plDt.Rows.Count > 0)
                        {
                            if ((plDt.Rows[0]["plType"].ToString() == "P-Pack" && plDt.Rows[0]["needPack"].ToString() == "0") ||
                                plDt.Rows[0]["plType"].ToString() != "P-Pack")
                            {
                                isEndGx(ppid, pgTable.Rows[0]["gxCode"].ToString(), ref gxIsEnd);
                            }
                            //isEndGx(ppid, pgTable.Rows[0]["gxCode"].ToString(), ref gxIsEnd);
                        }
                        #endregion

                        #region 存上报工工序 ppid 报工数量
                        if (gxIsEnd)
                        {
                            var ppidParGx = ppid + "," + parentGx;
                            if (!endGxDic.ContainsKey(ppidParGx))
                            {
                                var temDic = new Dictionary<string, string>();
                                temDic["number"] = number;
                                temDic["nNum"] = nNum;
                                endGxDic.Add(ppidParGx, temDic);
                            }
                            else
                            {
                                var temDic = (Dictionary<string, string>)endGxDic[ppidParGx];
                                temDic["number"] = (Convert.ToDecimal(temDic["number"].ToString()) + Convert.ToDecimal(number)).ToString("F2");
                                temDic["nNum"] = (Convert.ToDecimal(temDic["nNum"].ToString()) + Convert.ToDecimal(nNum)).ToString("F2"); ;
                                endGxDic[ppidParGx] = temDic;
                            }

                        }
                        #endregion
                    }
                }
                #endregion
                #region 判断修改生产计划子表的状态
                if (endGxDic != null && endGxDic.Count > 0)
                {
                    foreach (var key in endGxDic.Keys)
                    {
                        var teArr = key.Split(',');
                        var ppid = teArr[0];//计划单子表id
                        var parentGx = teArr[1]; //工序大类
                        var temDic = (Dictionary<string, string>)parentGxDic[key];
                        number = temDic["number"];
                        nNum = temDic["nNum"];
                        //获取计划数量
                        sb.Clear();
                        sb.Append("select number from pi_ProductionPlan_products where 1=1 and isdel<>1 ");
                        sb.Append(" and id=" + ppid + "");
                        var planDt = cmd.GetDataTable(sb.ToString());
                        var plNumber = 0.0;
                        if (planDt.Rows.Count > 0)
                        {
                            if (!string.IsNullOrWhiteSpace(planDt.Rows[0]["number"].ToString()))
                            {
                                plNumber = Convert.ToDouble(planDt.Rows[0]["number"].ToString());
                            }
                        }
                        sb.Clear();
                        sb.Append("select isnull(sum(convert(decimal(18,2),yNum)),0) yNum,isnull(sum(convert(decimal(18,2),nNum)),0) nNum  ");
                        sb.Append(" from pi_PlanBaogong_main where 1=1 and isDel<>1 ");
                        sb.Append(" and ppId ='" + ppid + "' and gxCode in(select gxCode ");
                        sb.Append(" from pi_ProductionPlan_process where 1=1 and ppId='" + ppid + "' and parentCode='" + parentGx + "') ");
                        var gxBgNumDt = cmd.GetDataTable(sb.ToString());
                        var totalNum = 0.0;//删除前的报工总数
                        var totalyNum = 0.0;//删除前的报工合格总数
                        if (gxBgNumDt != null && gxBgNumDt.Rows.Count > 0)
                        {
                            foreach (DataRow row in gxBgNumDt.Rows)
                            {
                                totalNum += (Convert.ToDouble(row["yNum"].ToString()) + Convert.ToDouble(row["nNum"].ToString()));
                                totalyNum += (Convert.ToDouble(row["yNum"].ToString()));
                            }
                        }
                        if (plNumber >= (totalNum - double.Parse(number) - double.Parse(nNum)))
                        {
                            if ( (checkGXs.Contains(parentGx) && plNumber > (totalyNum - double.Parse(number)) ) || !checkGXs.Contains(parentGx) )
                            {
                                //包装计划不按照是否报工完成来判定计划是否完成 （旧）
                                //包装计划如果未勾选是否包装，则报完工计划就完成，不需要打码 （新）
                                sb.Clear();
                                sb.Append("select * from V_ProductionPlan_products where 1=1 and id=" + ppid ); //+ "  and plType<>'P-Pack' "
                                var plDt = cmd.GetDataTable(sb.ToString());
                                if (plDt != null && plDt.Rows.Count > 0)
                                {
                                    if ((plDt.Rows[0]["plType"].ToString() == "P-Pack" && plDt.Rows[0]["needPack"].ToString() == "0") ||
                                       plDt.Rows[0]["plType"].ToString() != "P-Pack")
                                    {
                                        var pro = new DbProductionPlanPro();
                                        pro.id = int.Parse(ppid);
                                        pro.status = "ps-doing";
                                        oper = new OperateModel();
                                        oper.Data = pro;
                                        oper.Types = OperateModel.OperateType.Edit;
                                        oper.Conditions = "id";
                                        operList.Add(oper);
                                    }
                                    //var pro = new DbProductionPlanPro();
                                    //pro.id = int.Parse(ppid);
                                    //pro.status = "ps-doing";
                                    //oper = new OperateModel();
                                    //oper.Data = pro;
                                    //oper.Types = OperateModel.OperateType.Edit;
                                    //oper.Conditions = "id";
                                    //operList.Add(oper);
                                }
                            }
                        }
                    }
                }
                #endregion
                #region 判断每个计划工序的下一道工序的状态
                if (parentGxDic != null && parentGxDic.Count > 0)
                {
                    foreach (var key in parentGxDic.Keys)
                    {
                        #region 判断当前工序的下一道工序大类是否允许报工
                        var teArr = key.Split(',');
                        var ppid = teArr[0];//计划单子表id
                        var parentGx = teArr[1]; //工序大类
                        var temDic = (Dictionary<string, string>)parentGxDic[key];
                        number = temDic["number"];
                        nNum = temDic["nNum"];
                        sb.Clear();
                        sb.Append("select isnull(sum(convert(decimal(18,2),yNum)),0) yNum,isnull(sum(convert(decimal(18,2),nNum)),0) nNum  ");
                        sb.Append(" from pi_PlanBaogong_main where 1=1 and isDel<>1 ");
                        sb.Append(" and ppId ='" + ppid + "' and gxCode in(select gxCode ");
                        sb.Append(" from pi_ProductionPlan_process where 1=1 and ppId='" + ppid + "' and parentCode='" + parentGx + "') ");
                        var gxBgNumDt = cmd.GetDataTable(sb.ToString());
                        var totalNum = 0.0;//删除前的报工总数
                        var totalyNum = 0.0;//删除前的报工总合格数
                        if (gxBgNumDt != null && gxBgNumDt.Rows.Count > 0)
                        {
                            foreach (DataRow row in gxBgNumDt.Rows)
                            {
                                totalNum += (Convert.ToDouble(row["yNum"].ToString()) + Convert.ToDouble(row["nNum"].ToString()));
                                totalyNum += (Convert.ToDouble(row["yNum"].ToString()));
                            }
                        }

                        double temEndNum = 0;//删除后的剩余报工数
                        if (checkGXs.Contains(parentGx))
                        {
                            temEndNum = totalyNum - double.Parse(number);
                        }
                        else
                        {
                            temEndNum = totalNum - double.Parse(number) - double.Parse(nNum);
                        }
                        

                        var nextParentGx = temDic["nextParentGx"];
                        if (!string.IsNullOrWhiteSpace(nextParentGx) && temEndNum <= 0)
                        {
                            sb.Clear();
                            sb.Append("select * from pi_ProductionPlan_process where 1=1 and ppId='" + ppid + "' and parentCode='" + nextParentGx + "'");
                            sb.Append(" and isnull(canBg,0)<>0 ");
                            var gxtable = cmd.GetDataTable(sb.ToString());  //计划工序表
                            if (gxtable.Rows.Count > 0)
                            {
                                oper = new OperateModel();
                                var planProcess = new DbPlanGongXu();
                                planProcess.ppId = ppid;
                                planProcess.parentCode = nextParentGx;
                                planProcess.canBg = 0;
                                oper = new OperateModel();
                                oper.Data = planProcess;
                                oper.Types = OperateModel.OperateType.Edit;
                                oper.Conditions = "ppId,parentCode";
                                operList.Add(oper);
                            }
                        }
                        #endregion
                    }
                }
                #endregion
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 报工信息添加
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult AddBaoGongInfo(string datas, string isFrom = "PC", Dictionary<string, object> pars = null)
        {
            rsl = new ReturnResult();
            try
            {
                operList = new List<OperateModel>();
                var list = new List<DbPlanBaogongSub>();
                list.Add(JsonConvert.DeserializeObject<DbPlanBaogongSub>(datas));
                rsl = AddBaoGong(ref operList, JsonConvert.SerializeObject(list));
                if (!rsl.Result)
                {
                    return rsl;
                }
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 根据报工单添加报功记录
        /// </summary>
        /// <param name="datas"></param>
        /// <param name="isFrom"></param>
        /// <param name="pars"></param>
        /// <param name="operList"></param>
        /// <returns></returns>
        public ReturnResult AddBaoGong(ref List<OperateModel> operList, string datas, string isFrom = "PC", Dictionary<string, object> pars = null)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                var usCode = "";
                #region  通过来源（pc/app）获取创建人员
                if (pars != null)
                {
                    if (pars.ContainsKey("userCode") && !string.IsNullOrWhiteSpace(pars["userCode"].ToString()))
                    {
                        usCode = pars["userCode"].ToString();
                    }
                    else
                    {
                        rsl.Message = "参数错误：缺少创建人员信息";
                        return rsl;
                    }
                }
                else
                {
                    usCode = userLogin.UserInfo().userCode;
                }
                #endregion
                var bg_subs = JsonConvert.DeserializeObject<List<DbPlanBaogongSub>>(datas);
                if (bg_subs == null || bg_subs.Count < 1)
                {
                    rsl.Result = false;
                    rsl.Message = "未获取到报工的员工信息";
                    return rsl;
                }
                var bg_sub = bg_subs[0];
                double yNum = 0.0;
                double nNum = 0.0;
                sb.Append("select s.*,m.yNum yTotal,m.nNum nTotal,m.pKey,m.plCodes from");
                sb.Append(" pi_PlanBaogong_sub s inner join pi_PlanBaogong_main m on s.bgCode=m.bgCode");
                sb.Append(" where s.bgCode='" + bg_sub.bgCode + "'");
                var bgTable = cmd.GetDataTable(sb.ToString());
                sb.Clear();
                sb.Append("select * from pi_PlanPaiGong_info ");
                sb.Append("where tpCode='" + bgTable.Rows[0]["pKey"].ToString() + "'");
                var pgTable = cmd.GetDataTable(sb.ToString());
                if (pgTable.Rows.Count < 1)
                {
                    rsl.Message = "关联派工单" + bgTable.Rows[0]["pKey"].ToString() + "不存在";
                    return rsl;
                }
                if (pgTable.Rows.Count > 0 && pgTable.Rows[0]["isFinish"].ToString() != "0")
                {
                    rsl.Message = "关联派工单状态已发生改变";
                    return rsl;
                }
                //派工数量
                var pgNumber = 0.0;
                //生产计划子表id
                var ppid = pgTable.Rows[0]["ppId"].ToString();
                pgNumber = Convert.ToDouble(pgTable.Rows[0]["number"].ToString());
                #region 如果报工记录相关的计划有退料记录，不让新增报工记录
                sb.Clear();
                sb.Append("select * from pi_PaiGong_material_main where status = 'bl-in' and plCode like '%" + ppid + "%'");
                var tltable = cmd.GetDataTable(sb.ToString());
                if (tltable.Rows.Count > 0)
                {
                    rsl.Message = "当前报工记录相关的计划已将次品退回，</br>暂不支持新增报工记录。";
                    return rsl;
                }
                #endregion

                #region 获取派工单对应生产工序
                var pgx = new DbPlanGongXu();
                sb.Clear();
                sb.Append("select * from pi_ProductionPlan_process where 1=1 and ppId='" + ppid + "' and gxCode='" + pgTable.Rows[0]["gxCode"].ToString() + "'");
                var table = cmd.GetDataTable(sb.ToString());  //计划工序表
                var parentGx = "";
                if (table.Rows.Count > 0)
                {
                    parentGx = table.Rows[0]["parentCode"].ToString();
                    pgx = new DbPlanGongXu();
                    pgx.id = int.Parse(table.Rows[0]["id"].ToString());
                }
                else
                {
                    rsl.Message = "数据错误，找不到派工单对应的工艺";
                    return rsl;
                }
                #endregion

                #region 修改数据
                var jsons = JsonConvert.DeserializeObject<List<JObject>>(datas);
                if (string.IsNullOrWhiteSpace(jsons[0]["yNum"].ToString()))
                {
                    rsl.Message = "请录入合格数";
                    return rsl;
                }
                if (string.IsNullOrWhiteSpace(jsons[0]["nNum"].ToString()))
                {
                    jsons[0]["nNum"] = "0";
                }

                var defNumber = ""; var defnNumber = "";
                if (pars != null)//app
                {
                    defNumber = jsons[0]["number"].ToString();//输入的合格数
                    defnNumber = jsons[0]["disNumber"].ToString();//输入的不合格数
                }
                else//pc
                {
                    defNumber = jsons[0]["yNum"].ToString();//输入的合格数
                    defnNumber = jsons[0]["nNum"].ToString();//输入的不合格数
                }
                //var defNumber = jsons[0]["number"].ToString();//输入的合格数
                //var defnNumber = jsons[0]["disNumber"].ToString();//输入的不合格数
                var temyTotal = 0.0;
                var temnTotal = 0.0;
                foreach (var obj in jsons)
                {
                    string tmyNum = "0", tmnNum = "0";
                    if (!string.IsNullOrWhiteSpace(obj["yNum"].ToString()))
                    {
                        tmyNum = obj["yNum"].ToString();
                    }
                    if (!string.IsNullOrWhiteSpace(obj["nNum"].ToString()))
                    {
                        tmnNum = obj["nNum"].ToString();
                    }
                    temyTotal += double.Parse(tmyNum);
                    temnTotal += double.Parse(tmnNum);
                }
                var temcY = Math.Round(double.Parse(defNumber) - temyTotal, 2);
                var temcN = Math.Round(double.Parse(defnNumber) - temnTotal, 2);
                rsl = this.updateNum(jsons, temcY, "yNum");
                if (!rsl.Result)
                {
                    return rsl;
                }
                rsl = this.updateNum(jsons, temcN, "nNum");
                if (!rsl.Result)
                {
                    return rsl;
                }
                rsl.Result = false;//清空状态
                #endregion
                bg_subs = JsonConvert.DeserializeObject<List<DbPlanBaogongSub>>(JsonConvert.SerializeObject(jsons));
                foreach (var item in bg_subs)
                {
                    #region  非空验证
                    if (string.IsNullOrWhiteSpace(item.userCode))
                    {
                        rsl.Message = "请先选择员工";
                        return rsl;
                    }
                    if (string.IsNullOrWhiteSpace(item.yNum))
                    {
                        rsl.Message = "请录入合格数";
                        return rsl;
                    }
                    if (string.IsNullOrWhiteSpace(item.nNum))
                    {
                        rsl.Message = "请录入不合格数";
                        return rsl;
                    }
                    #endregion

                    #region 检测人员是否已添加
                    sb.Clear();
                    sb.Append(" select id from pi_PlanBaogong_sub where 1=1 and userCode='" + item.userCode + "' ");
                    sb.Append(" and bgCode='" + bg_sub.bgCode + "' and isdel<>1 ");
                    var uDt = cmd.GetDataTable(sb.ToString());
                    if (uDt != null && uDt.Rows.Count > 0)
                    {
                        rsl.Message = "人员编码：" + item.userCode + "已报工，不能重复报工";
                        return rsl;
                    }
                    #endregion

                    #region 子表数据添加
                    item.createuser = usCode;
                    item.gxCode = bgTable.Rows[0]["gxCode"].ToString();
                    item.happenDate = bgTable.Rows[0]["happenDate"].ToString();
                    item.createtime = getNow();
                    item.isdel = 0;
                    item.isFrom = isFrom;
                    oper = new OperateModel();
                    oper.Data = item;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);
                    #endregion
                    yNum += double.Parse(item.yNum);
                    nNum += double.Parse(item.nNum);

                    #region 绩效信息添加
                    sb.Clear();
                    sb.Append("select * from fun_GxPrice_info ");
                    sb.Append("where isdel=0 and cgxCode='" + bgTable.Rows[0]["gxCode"] + "'");
                    var wgTable = cmd.GetDataTable(sb.ToString());//获取报工工序的绩效单价
                    var wage = new DbemployeeWage();
                    wage.bgType = "BG";
                    wage.createtime = getNow();
                    wage.createuser = usCode;
                    wage.dataId = bgTable.Rows[0]["pKey"].ToString();
                    wage.gxCode = bgTable.Rows[0]["gxCode"].ToString();
                    wage.happenDate = bgTable.Rows[0]["happenDate"].ToString();
                    wage.isdel = 0;
                    wage.userCode = item.userCode;
                    wage.status = "approving";
                    wage.memo = "生产报工绩效(添加)";
                    wage.yNum = item.yNum;
                    wage.nNum = item.nNum;
                    wage.plCode = bgTable.Rows[0]["plCodes"].ToString();
                    wage.uPrice = string.Format("{0}/{1}", wgTable.Rows[0]["yPrice"].ToString(), wgTable.Rows[0]["nPrice"].ToString());
                    wage.wType = "BG";
                    wage.bgCode = bgTable.Rows[0]["bgCode"].ToString(); ;
                    wage.total = (double.Parse(wgTable.Rows[0]["yPrice"].ToString()) * double.Parse(item.yNum) + double.Parse(wgTable.Rows[0]["nPrice"].ToString()) * double.Parse(item.nNum)).ToString();
                    oper = new OperateModel();
                    oper.Data = wage;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);
                    #endregion
                }
                var yTNum = yNum + double.Parse(bgTable.Rows[0]["yTotal"].ToString());
                var nTNum = nNum + double.Parse(bgTable.Rows[0]["nTotal"].ToString());
                #region 报工主表信息修改
                DbPlanBaogongMain bg_main = new DbPlanBaogongMain();
                bg_main.bgCode = bg_sub.bgCode;
                bg_main.yNum = yTNum.ToString();
                bg_main.nNum = nTNum.ToString();
                oper = new OperateModel();
                oper.Data = bg_main;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "bgCode";
                operList.Add(oper);
                #endregion

                var onlyY = false;
                #region 补货改标记录
                if (nTNum > 0)
                {
                    #region 根据pi_restock_info的status判断新增的记录的数量是取总报工数量还是每次明细的数量
                    sb.Clear();
                    sb.Append("select * from pi_restock_info where isdel=0 and dataType='restock' and bgCode='" + bg_sub.bgCode + "'");
                    var rTable = cmd.GetDataTable(sb.ToString()); //记录表
                    if (rTable.Rows.Count > 0)
                    {
                        // 如果pi_restock_info表中有报工单的记录，则说明当前派工单是在补货改标的工序中，可以进行记录的新增修改操作

                        //如果报工工序涉及到补货改标的工序，改变计划状态时只看合格数是否足够
                        onlyY = true;

                        var oCount = rTable.Select("status='0'");
                        var lCount = rTable.Select("status='1'");

                        var num = "";
                        if (lCount.Length > 0)
                        {
                            //报工单有已汇总到任务中心的记录，那新增的records的合格数就不能是总数了，得是每次添加的明细数量+status=0的数量
                            if (oCount.Length > 0)
                                num = (nNum + double.Parse(oCount[0]["number"].ToString())).ToString();
                            else
                                num = nNum.ToString();
                        }
                        else
                        {
                            num = nTNum.ToString();
                        }
                        #endregion

                        DbRestockInfo r = new DbRestockInfo();
                        r.bgCode = bg_sub.bgCode;
                        r.dataType = "restock";
                        if (rTable.Rows.Count > 0)
                        {
                            //修改
                            r.number = num;
                            oper = new OperateModel();
                            oper.Data = r;
                            oper.Types = OperateModel.OperateType.Edit;
                            oper.Conditions = "bgCode,dataType";
                        }
                        else
                        {
                            //新增
                            rsl = UnqualifiedInfo(
                           pgTable.Rows[0]["gxCode"].ToString(),
                           num,
                            pgTable.Rows[0]["tpCode"].ToString(),
                           bg_sub.bgCode,
                           usCode,
                           ref operList);

                            if (!rsl.Result)
                            {
                                return rsl;
                            }
                            rsl.Result = false;
                        }
                        operList.Add(oper);

                    }

                }
                #endregion

                #region 入库记录
                if (pgTable.Rows[0]["isNeedIn"].ToString().Equals("1"))
                {
                    #region 根据pi_restock_info的status判断新增的记录的数量是取总报工数量还是每次明细的数量
                    sb.Clear();
                    sb.Append("select * from pi_restock_info where isdel=0 and dataType='inKuTask' and bgCode='" + bg_sub.bgCode + "'");
                    var rTable = cmd.GetDataTable(sb.ToString()); //记录表

                    var oCount = rTable.Select("status='0'");
                    var lCount = rTable.Select("status='1'");

                    var num = "";
                    if (lCount.Length > 0)
                    {
                        //报工单有已汇总到任务中心的记录，那新增的records的合格数就不能是总数了，得是每次添加的明细数量+status=0的数量
                        if (oCount.Length > 0)
                            num = (yNum+double.Parse(oCount[0]["number"].ToString())).ToString();
                        else
                            num = yNum.ToString();
                    }
                    else
                    {
                        num = yTNum.ToString();
                    }
                    #endregion

                    DbRestockInfo r = new DbRestockInfo();
                    r.bgCode = bg_sub.bgCode;
                    r.dataType = "inKuTask";
                    if (oCount.Length > 0)
                    {
                        //修改
                        r.number = num;
                        oper = new OperateModel();
                        oper.Data = r;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "bgCode,dataType";
                    }
                    else
                    {
                        //新增
                        rsl = addInKuInfo(bg_sub.bgCode, pgTable.Rows[0]["tpCode"].ToString(), pgTable.Rows[0]["wareCode"].ToString(), num, usCode, ref operList);
                        if (!rsl.Result)
                        {
                            return rsl;
                        }
                        rsl.Result = false;
                    }
                    //oper = new OperateModel();
                    //DbRestockInfo r = new DbRestockInfo();
                    //r.bgCode = bg_sub.bgCode;
                    //r.number = yTNum.ToString();
                    //r.dataType = "inKuTask";
                    //oper.Data = r;
                    //oper.Types = OperateModel.OperateType.Edit;
                    //oper.Conditions = "bgCode,dataType";
                    operList.Add(oper);
                }
                #endregion


                #region 获取上道工序的合格数
                string bNum = "1", bnNum = "0", msg = "", bgxCode = "";
                var gxIsEnd = false;
                this.CheckBackGxYnum(bgTable.Rows[0]["pKey"].ToString(), ref bNum, ref bnNum, ref msg, ref gxIsEnd, ref bgxCode);
                if (string.IsNullOrWhiteSpace(bNum))
                {
                    rsl.Message = msg;
                    return rsl;
                }
                #endregion

                //是否为最后一道工序大类
                //isEndGx(ppid, pgTable.Rows[0]["gxCode"].ToString(), ref gxIsEnd);

                #region 派工单是否完成
                sb.Clear();

                if (pgTable.Rows.Count > 0)
                {
                    sb.Clear();
                    sb.Append("select isnull(sum(convert(decimal(18,1),yNum)),'0') yNum,isnull(sum(convert(decimal(18,1),nNum)),'0') nNum   ");
                    sb.Append(" from pi_PlanBaogong_main where isdel=0 and ");
                    sb.Append(" pKey='" + bgTable.Rows[0]["pKey"].ToString() + "' and bgCode !='" + bg_sub.bgCode + "'");
                    var jsTable = cmd.GetDataTable(sb.ToString());
                    double js = double.Parse(jsTable.Rows[0]["yNum"].ToString()) + double.Parse(jsTable.Rows[0]["nNum"].ToString()) + double.Parse(bg_main.yNum) + double.Parse(bg_main.nNum);
                    if (double.Parse(bNum) < js)
                    {
                        rsl.Message = "此工序报工总数不得大于上道工序报工合格数：</br>" + bNum;
                        return rsl;
                    }
                    if (pgNumber < js)
                    {
                        rsl.Message = "此工序报工总数不得大于派工数：</br>" + bNum;
                        return rsl;
                    }
                    if (double.Parse(pgTable.Rows[0]["number"].ToString()) <= js)
                    {
                        DbPlanPaiGong chan = new DbPlanPaiGong();
                        chan.isFinish = 1;
                        chan.finishtime = getNow();
                        chan.id = int.Parse(pgTable.Rows[0]["id"].ToString());
                        oper = new OperateModel();
                        oper.Data = chan;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "id";
                        operList.Add(oper);
                        //修改工序状态
                        pgx.status = "ps-finish";

                    }
                    else
                    {
                        pgx.status = "ps-doing";
                    }
                    oper = new OperateModel();
                    oper.Data = pgx;
                    oper.Conditions = "id";
                    oper.Types = OperateModel.OperateType.Edit;
                    operList.Add(oper);
                }
                #endregion

                #region 判断当前工序的下一道工序大类是否允许报工
                var nextParentGx = "";
                getNextGx(ppid, pgTable.Rows[0]["gxCode"].ToString(), ref nextParentGx);
                if (!string.IsNullOrWhiteSpace(nextParentGx))
                {
                    sb.Clear();
                    sb.Append("select * from pi_ProductionPlan_process where 1=1 and ppId='" + ppid + "' and parentCode='" + nextParentGx + "'");
                    sb.Append(" and isnull(canBg,0)<>1 ");
                    var gxtable = cmd.GetDataTable(sb.ToString());  //计划工序表
                    if (gxtable.Rows.Count > 0)
                    {
                        oper = new OperateModel();
                        var planProcess = new DbPlanGongXu();
                        planProcess.ppId = ppid;
                        planProcess.parentCode = nextParentGx;
                        planProcess.canBg = 1;
                        oper = new OperateModel();
                        oper.Data = planProcess;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "ppId,parentCode";
                        operList.Add(oper);
                    }
                }
                #endregion


                #region 判断生产计划是否完成
                sb.Clear();
                sb.Append("select number from pi_ProductionPlan_products where 1=1 and isdel<>1 ");
                sb.Append(" and id=" + ppid + "");
                var planDt = cmd.GetDataTable(sb.ToString());
                var plNumber = 0.0;
                if (planDt.Rows.Count > 0)
                {
                    if (!string.IsNullOrWhiteSpace(planDt.Rows[0]["number"].ToString()))
                    {
                        plNumber = Convert.ToDouble(planDt.Rows[0]["number"].ToString());
                    }
                }
                var dic = new Dictionary<string, object>();
                dic["ppid"] = ppid.ToString();
                dic["parentGx"] = parentGx.ToString();
                dic["yTotal"] = yTNum;
                dic["nTotal"] = nTNum;
                dic["plNumber"] = plNumber;
                dic["nBgCode"] = bg_sub.bgCode;//防止出现脏读数据，统计数据时需要排除当下派工单数据

                //包装计划不按照是否报工完成来判定计划是否完成 （旧）
                //包装计划如果未勾选是否包装，则报完工计划就完成，不需要打码 （新）
                sb.Clear();
                sb.Append("select * from V_ProductionPlan_products where 1=1 and id=" + ppid);   //+ "  and plType<>'P-Pack' "
                var plDt = cmd.GetDataTable(sb.ToString());
                if (plDt != null && plDt.Rows.Count > 0)
                {
                    if ((plDt.Rows[0]["plType"].ToString() == "P-Pack" && plDt.Rows[0]["needPack"].ToString() == "0") ||
                        plDt.Rows[0]["plType"].ToString() != "P-Pack")
                    {
                        ChanagePlanStatus(gxIsEnd, dic, ref operList, onlyY);
                    }

                    //ChanagePlanStatus(gxIsEnd, dic, ref operList);
                }
                #endregion

                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 生产计划字表中该工序是否属于最后一道工序大类里的
        /// </summary>
        /// <param name="ppid"></param>
        /// <param name="gxCode"></param>
        /// <param name="gxIsEnd"></param>
        private void isEndGx(string ppid, string gxCode, ref bool gxIsEnd)
        {
            #region 判定当前工序是否为最后一个工序
            StringBuilder sb = new StringBuilder();
            sb.Clear();
            sb.Append("select * from pi_ProductionPlan_process where 1=1 and ppId='" + ppid + "' and gxCode='" + gxCode + "'");
            var table = cmd.GetDataTable(sb.ToString());  //计划工序表
            var parentGx = "";
            if (table.Rows.Count > 0)
            {
                parentGx = table.Rows[0]["parentCode"].ToString();
            }
            sb.Clear();
            sb.Append("select cCode,orderNum from fun_CommonData_Info");
            sb.Append(" where cType='GX' and isdel=0 and status='Y' and ");
            sb.Append(" cCode in(select case isChild when '0' then gxCode when '1' then parentCode end as gxCode ");
            sb.Append("from pi_ProductionPlan_process where 1=1 and ppId='" + ppid + "' )");
            sb.Append(" order by orderNum asc");
            var fgxTable = cmd.GetDataTable(sb.ToString());
            if (fgxTable.Rows.Count > 0)
            {
                for (int i = 0; i < fgxTable.Rows.Count; i++)
                {
                    if (fgxTable.Rows[i]["cCode"].ToString().Equals(parentGx))
                    {
                        if (i == (fgxTable.Rows.Count - 1))
                        {
                            gxIsEnd = true;
                        }
                    }
                }
            }
            #endregion
        }
        /// <summary>
        /// 生产计划字表中该工序所属大类的下一个工序大类
        /// </summary>
        /// <param name="ppid"></param>
        /// <param name="gxCode"></param>
        /// <param name="gxIsEnd"></param>
        private void getNextGx(string ppid, string gxCode, ref string nextParentGx)
        {
            #region 判定当前工序的下一道工序大类
            StringBuilder sb = new StringBuilder();
            sb.Clear();
            sb.Append("select * from pi_ProductionPlan_process where 1=1 and ppId='" + ppid + "' and gxCode='" + gxCode + "'");
            var table = cmd.GetDataTable(sb.ToString());  //计划工序表
            var parentGx = "";
            if (table.Rows.Count > 0)
            {
                parentGx = table.Rows[0]["parentCode"].ToString();
            }
            sb.Clear();
            sb.Append("select cCode,orderNum from fun_CommonData_Info");
            sb.Append(" where cType='GX' and isdel=0 and status='Y' and ");
            sb.Append(" cCode in(select case isChild when '0' then gxCode when '1' then parentCode end as gxCode ");
            sb.Append("from pi_ProductionPlan_process where 1=1 and ppId='" + ppid + "'  )");
            sb.Append(" order by orderNum asc");
            var fgxTable = cmd.GetDataTable(sb.ToString());
            if (fgxTable.Rows.Count > 1)
            {
                for (int i = 0; i < fgxTable.Rows.Count; i++)
                {
                    if (fgxTable.Rows[i]["cCode"].ToString().Equals(parentGx))
                    {
                        if (i < (fgxTable.Rows.Count - 1))
                        {
                            nextParentGx = fgxTable.Rows[i + 1]["cCode"].ToString();
                            break;
                        }
                    }
                }
            }
            #endregion
        }
        /// <summary>
        /// 备料表
        /// </summary>
        /// <param name="condition">检索条件</param>
        /// <returns></returns>
        public ReturnResult BeiLiaoList(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
                var maxR = getMaxRole();

                sb.Append(" isdel=0 and status<>'bl-in' ");

                if (userLogin.UserInfo().isAdmin == 0 && !userLogin.UserInfo().powerRole.Equals(maxR) )
                {
                    sb.Append(" and  createuser='" + userLogin.UserInfo().userCode + "' or users like '%" + userLogin.UserInfo().userName + "%'");
                }
                foreach (JProperty obj in json.Properties())
                {
                    if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                    {
                        if (obj.Name == "status")
                        {
                            continue;
                        }
                        if (!string.IsNullOrWhiteSpace(sb.ToString()))
                        {
                            sb.Append(" and ");
                        }
                        if (obj.Name == "cStatus")
                        {
                            var sArr = obj.Value.ToString().Split(',');
                            string status = "";
                            foreach (string s in sArr)
                            {
                                if (!string.IsNullOrWhiteSpace(s))
                                {
                                    status += "'" + s + "',";
                                }
                            }
                            sb.Append("status in (" + status.TrimEnd(',') + ")");
                        }
                        else
                        {
                            sb.Append(obj.Name + "='" + obj.Value + "' ");
                        }

                    }
                }
                var list = cmd.PageList("V_BeiLiao_Info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);

                rsl.Result = true;
                rsl.Data = list;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 退料表
        /// </summary>
        /// <param name="condition">检索条件</param>
        /// <returns></returns>
        public ReturnResult TuiLiaoList(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
                var maxR = getMaxRole();

                sb.Append(" isdel=0 and status='bl-in' ");

                if (userLogin.UserInfo().isAdmin == 0 && !userLogin.UserInfo().powerRole.Equals(maxR) )
                {
                    sb.Append(" and  createuser='" + userLogin.UserInfo().userCode + "' or users like '%" + userLogin.UserInfo().userName + "%'");
                }

                var list = cmd.PageList("V_BeiLiao_Info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);

                foreach (var s in list)
                {
                    sb.Clear();
                    sb.Append("select plCode from pi_ProductionPlan_products where id in (" + s["plCode"] + ")");
                    var plTable = cmd.GetDataTable(sb.ToString());
                    var plCode = "";
                    foreach (DataRow dr in plTable.Rows)
                    {
                        plCode += dr[0] + ",";
                    }
                    s["plCode"] = plCode.TrimEnd(',');
                }

                if (!string.IsNullOrWhiteSpace(json["plCode"].ToString()))
                {
                    var newList = list.Where(t => t["plCode"].IndexOf(json["plCode"].ToString()) > -1).ToList();
                    list = newList;
                }

                rsl.Result = true;
                rsl.Data = list;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 备料明细
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult BeiLiaoDetail(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select s.*,i.proName ,w.houseName wareName,c.cName positonName,s.cu_color,s.cu_shangbiao ");
                sb.Append("from pi_PaiGong_material_sub s ");
                sb.Append("inner join  fun_Inventory_Info i on i.proCode=s.proCode ");
                sb.Append("inner join fun_WareHouse_Info w on w.houseCode=s.wareCode ");
                sb.Append("left join fun_CommonData_Info c on c.cCode=s.positionCode and c.cType='WP' ");
                #region 检索条件
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    if (!string.IsNullOrWhiteSpace(json["pmCode"].ToString()))
                    {
                        var pmCode = "";
                        if (json["pmCode"].ToString().Contains(","))
                        {
                            foreach (var s in json["pmCode"].ToString().Split(','))
                            {
                                pmCode += "'" + s + "',";
                            }
                        }
                        else
                            pmCode = "'" + json["pmCode"].ToString() + "'";

                        sb.Append(" where pmCode in (" + pmCode.TrimEnd(',') + ")");
                    }
                }
                #endregion
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 退料存货明细
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult TuiLiaoDetail(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                var ids = ""; var pmCode = "";
                #region 检索条件
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    if (!string.IsNullOrWhiteSpace(json["pmCode"].ToString()))
                    {
                        pmCode = json["pmCode"].ToString();
                        sb.Append("select plCode from pi_PaiGong_material_main where pmCode='" + pmCode + "'");
                        ids = cmd.GetDataTable(sb.ToString()).Rows[0][0].ToString();
                    }
                }
                #endregion
                sb.Clear();
                sb.Append("select p.id,p.plCode,p.proCode,proName,p.cu_shangbiao,cu_yanse cu_color,spec,s.wareCode,");
                sb.Append("w.houseName wareName, s.positionCode,c.cName positionName,pmCode,s.number ");
                sb.Append("from V_ProductionPlan_products p inner join pi_PaiGong_material_sub s on s.proCode = p.proCode ");
                sb.Append("inner join fun_WareHouse_Info w on w.houseCode = s.wareCode ");
                sb.Append("left join fun_CommonData_Info c on c.cCode = s.positionCode and c.cType = 'WP' ");
                sb.Append("where p.isdel=0 and p.id in (" + ids + ") and pmCode ='" + pmCode + "'");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 不合格品明细
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult ciPinDetail(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                sb.Append("select row_number()over(order by SUM(CONVERT(decimal(18, 2), m.nNum)) desc ) id, ");
                sb.Append("p.prlCode,p.proCode,p.proName,cu_shangbiao,cu_yanse,spec, ");
                sb.Append("SUM(CONVERT(decimal(18, 2), m.nNum)) nNum ,SUM(CONVERT(decimal(18, 2), m.nNum)) bakNum ");
                sb.Append("from pi_PlanBaogong_main m ");
                sb.Append("inner join V_ProductionPlan_products p on p.id = m.ppId ");
                sb.Append(" where m.ppId in (" + json["ids"].ToString() + ") and m.isDel = 0 ");
                sb.Append("group by p.prlCode,p.proCode,p.proName,cu_shangbiao,cu_yanse,spec ");
                var table = cmd.GetDataTable(sb.ToString());

                table.Columns.Add("houseCode");
                table.Columns.Add("houseName");
                table.Columns.Add("positionCode");
                table.Columns.Add("positionName");

                ////用于选择仓库后更新表格显示内容
                //if (json["rows"] != null)
                //{
                //    for (int i = 0; i < table.Rows.Count; i++)
                //    {
                //        if (json["rows"].ToString().Contains(table.Rows[i]["id"].ToString()))
                //        {
                //            table.Rows[i]["houseCode"] = json["houseCode"].ToString();
                //            table.Rows[i]["houseName"] = json["houseName"].ToString();
                //        }
                //    }
                //}

                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

         /// <summary>
        /// 不合格品明细
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult ciPinDetails(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                sb.Append("select row_number()over(order by SUM(CONVERT(decimal(18, 2), m.nNum)) desc ) id, ");
                sb.Append("p.prlCode,p.proCode,p.proName,cu_shangbiao,cu_yanse,spec, ");
                sb.Append("SUM(CONVERT(decimal(18, 2), m.nNum)) nNum ,SUM(CONVERT(decimal(18, 2), m.nNum)) bakNum ");
                sb.Append("from pi_PlanBaogong_main m ");
                sb.Append("inner join V_ProductionPlan_products p on p.id = m.ppId ");
                sb.Append(" where m.ppId in (" + json["ids"].ToString() + ") and m.isDel = 0 ");
                sb.Append("group by p.prlCode,p.proCode,p.proName,cu_shangbiao,cu_yanse,spec ");
                var table = cmd.GetDataTable(sb.ToString());

                table.Columns.Add("houseCode");
                table.Columns.Add("houseName");
                table.Columns.Add("positionCode");
                table.Columns.Add("positionName");

                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        //获取备料的出库类型和入库类型
        public DataTable getBLType()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select * from sys_parameters_info where parCode like 'bl_%Type'");
            return cmd.GetDataTable(sb.ToString());
        }

        /// <summary>
        /// 备料单出库完成
        /// </summary>
        /// <param name="pmCode"></param>
        /// <returns></returns>
        public ReturnResult BeiLiaoFinish(string pmCodes)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                #region 生成调拨单
                #region  获取备料单编码（拼接）
                var code = "";
                var pmCode = pmCodes.Split(',');
                foreach (string r in pmCode)
                {
                    code = code + "'" + r + "',";
                }
                #endregion
                #region 获取备料单信息
                StringBuilder sb = new StringBuilder();

                #region 如果不是组合套装备料
                sb.Append("select s.wareCode,s.positionCode,s.proCode,i.proName,SUM(CONVERT(decimal(18,0),s.number)) number, ");
                sb.Append("s.cu_color color,s.cu_shangbiao shangbiao,m.plCode ");
                sb.Append(" from pi_PaiGong_material_main m ");
                sb.Append(" inner join pi_PaiGong_material_sub s on s.pmCode = m.pmCode and s.isdel=0 and m.istz=0 ");
                sb.Append(" inner join fun_Inventory_Info i on i.proCode = s.proCode ");
                sb.Append(" where m.isdel=0 and m.pmCode in (" + code.TrimEnd(',') + ") ");
                sb.Append("group by s.wareCode,s.positionCode,s.proCode,i.proName,s.cu_color,s.cu_shangbiao,m.plCode");
                var blTable = cmd.GetDataTable(sb.ToString());
                #endregion

                #region 如果是组合套装备料
                #region 获取套装的入库仓库， 即备料时出库仓库
                var ware = "";//入库仓库
                sb.Clear();
                sb.Append("select parCode, parValue from sys_parameters_info ");
                sb.Append("where parCode = 'tzrkck' and isdel = 0 and enable = 'open' ");
                var wareTable = cmd.GetDataTable(sb.ToString());
                if (wareTable.Rows.Count > 0)
                {
                    ware = wareTable.Rows[0]["parValue"].ToString();
                }
                else
                {
                    ware = "012";//图强备货库
                }
                #endregion

                sb.Clear();
                sb.Append("select '" + ware + "' wareCode,'' positionCode,p.proCode,p.proName,");
                sb.Append("SUM(CONVERT(decimal(18, 0), p.number)) number,p.cu_yanse color, p.cu_shangbiao shangbiao, m.plCode ");
                sb.Append("from pi_PaiGong_material_main m inner join V_ProductionPlan_products p on p.plCode = m.plCode ");
                sb.Append("and p.rowNO = m.rowNo and p.isdel=0 and m.istz = 1 ");
                sb.Append("where m.isdel=0 and m.pmCode in (" + code.TrimEnd(',') + ") ");
                sb.Append("group by p.proCode,p.proName,p.cu_yanse,p.cu_shangbiao,m.plCode ");
                var tzTable = cmd.GetDataTable(sb.ToString());
                #endregion

                #region 汇总备料表
                var cloTable = blTable.Clone();
                object[] obj = new object[cloTable.Columns.Count];
                for (int i = 0; i < blTable.Rows.Count; i++)
                {
                    blTable.Rows[i].ItemArray.CopyTo(obj, 0);
                    cloTable.Rows.Add(obj);
                }
                for (int i = 0; i < tzTable.Rows.Count; i++)
                {
                    tzTable.Rows[i].ItemArray.CopyTo(obj, 0);
                    cloTable.Rows.Add(obj);
                }
                #endregion

                #endregion

                #region 获取转出仓库（去重后的）
                List<string> warelist = new List<string>();
                foreach (DataRow dr in cloTable.Rows)
                {
                    if (!warelist.Contains(dr["wareCode"].ToString()))
                        warelist.Add(dr["wareCode"].ToString());
                }
                #endregion
                #region 获取转入仓库（客户参数）
                sb.Clear();
                sb.Append(" select parValue from sys_parameters_info where parCode='dbzrck' ");
                var parTable = cmd.GetDataTable(sb.ToString());
                var inware = "";
                if (parTable.Rows.Count > 0)
                    inware = parTable.Rows[0][0].ToString();
                else
                    inware = "bcp";
                #endregion
                #region 获取发生类别
                var inType = "107"; var outType = "207";
                var typeTable = getBLType();
                if (typeTable.Rows.Count > 0)
                {
                    foreach (DataRow dr in typeTable.Rows)
                    {
                        if (dr["parCode"].Equals("bl_InType"))
                            inType = dr["parValue"].ToString();
                        else if (dr["parCode"].Equals("bl_OutType"))
                            outType = dr["parValue"].ToString();
                    }
                }
                #endregion
                U8_13 u8 = new U8_13();
                rsl = new ReturnResult();
                //rsl = u8.MaterialOut(cloTable);
                rsl = u8.TransVouchDirect(cloTable, warelist, inware, inType, outType);
                #region   提示信息,返写单号
                if (rsl.Result)
                {
                    sb.Clear();
                    sb.Append("update pi_PaiGong_material_main set relationBar='" + rsl.Data + "' where pmCode in (" + code.TrimEnd(',') + ")");
                    rsl = cmd.UpdateSql(sb.ToString());

                    if (rsl.Result)
                    {
                        #region  修改状态
                        foreach (string r in pmCode)
                        {
                            if (!string.IsNullOrWhiteSpace(r))
                            {
                                #region 备料主表
                                DbPGMaterialMain mater;
                                mater = new DbPGMaterialMain();
                                mater.pmCode = r;
                                mater.status = "bl-out";
                                oper = new OperateModel();
                                oper.Data = mater;
                                oper.Types = OperateModel.OperateType.Edit;
                                oper.Conditions = "pmCode";
                                operList.Add(oper);
                                #endregion

                                #region 备料子表
                                DbPGMaterialSub sub = new DbPGMaterialSub();
                                sub = new DbPGMaterialSub();
                                sub.pmCode = r;
                                sub.status = "bl-out";
                                oper = new OperateModel();
                                oper.Data = sub;
                                oper.Types = OperateModel.OperateType.Edit;
                                oper.Conditions = "pmCode";
                                operList.Add(oper);
                                #endregion
                            }
                        }
                        if (operList.Count > 0)
                        {
                            rsl = cmd.MoreUpdate(operList);
                        }
                        else
                        {
                            rsl.Message = "修改备料单状态错误，没有数据！";
                            return rsl;
                        }
                        #endregion
                    }
                    else
                    {
                        rsl.Message = "回写单号错误！";
                        return rsl;
                    }

                }
                else
                {
                    return rsl;
                }
                #endregion
                #endregion

                #region
                //#region 状态修改
                //var pmCode = pmCodes.Split(',');
                //foreach (string r in pmCode)
                //{
                //    if (!string.IsNullOrWhiteSpace(r))
                //    {
                //        #region 备料主表
                //        DbPGMaterialMain mater;
                //        mater = new DbPGMaterialMain();
                //        mater.pmCode = r;
                //        mater.status = "bl-out";
                //        oper = new OperateModel();
                //        oper.Data = mater;
                //        oper.Types = OperateModel.OperateType.Edit;
                //        oper.Conditions = "pmCode";
                //        operList.Add(oper);
                //        #endregion

                //        #region 备料子表
                //        DbPGMaterialSub sub = new DbPGMaterialSub();
                //        sub = new DbPGMaterialSub();
                //        sub.pmCode = r;
                //        sub.status = "bl-out";
                //        oper = new OperateModel();
                //        oper.Data = sub;
                //        oper.Types = OperateModel.OperateType.Edit;
                //        oper.Conditions = "pmCode";
                //        operList.Add(oper);
                //        #endregion

                //        if (operList.Count > 0)
                //        {
                //            rsl = cmd.MoreUpdate(operList);
                //        }
                //        else
                //        {
                //            rsl.Message = "没有数据";
                //        }
                //    }
                //}
                //#endregion
                //if (operList.Count > 0)
                //{
                //    rsl = cmd.MoreUpdate(operList);

                //    #region 生成材料出库单
                //    if (rsl.Result)
                //    {
                //        StringBuilder sb = new StringBuilder();
                //        sb.Append("select m.pmCode,s.wareCode,s.proCode,w.houseName,i.proName,SUM(CONVERT(decimal(18,0),s.number)) number ");
                //        sb.Append("from pi_PaiGong_material_main m ");
                //        sb.Append("inner join pi_PaiGong_material_sub s on s.pmCode = m.pmCode ");
                //        sb.Append("inner join fun_Inventory_Info i on i.proCode = s.proCode ");
                //        sb.Append("where m.pmCode in ('" + pmCodes + ") ");
                //        sb.Append("group by m.pmCode,s.wareCode,s.proCode,w.houseName,i.proName");
                //        var cloTable = cmd.GetDataTable(sb.ToString());

                //        U8_13 u8 = new U8_13();
                //        rsl = new ReturnResult();
                //        rsl = u8.MaterialOut(cloTable);
                //        #region   提示信息,返写单号
                //        if (rsl.Result)
                //        {
                //            sb.Clear();
                //            sb.Append("update pi_PaiGong_material_main set relationBar='" + rsl.Data + "' where pmCode in ('" + pmCodes + "')");
                //            rsl = cmd.UpdateSql(sb.ToString());
                //        }
                //        else
                //        {
                //            rsl.Message = "生成材料出库单失败！";
                //        }
                //        #endregion
                //    }
                //    else
                //    {
                //        rsl.Message = "状态修改错误";
                //    }
                //    #endregion

                //}
                //else
                //{
                //    rsl.Message = "没有数据";
                //}
                #endregion
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 删除备料单
        /// </summary>
        /// <param name="pmCode"></param>
        /// <returns></returns>
        public ReturnResult DelBeiLiaoByCode(string pmCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                #region 备料主表
                DbPGMaterialMain mater;
                mater = new DbPGMaterialMain();
                mater.pmCode = pmCode;
                mater.isdel = 1;
                mater.delUser = userLogin.UserInfo().userCode; ;
                mater.delDate = getNow(); ;
                oper = new OperateModel();
                oper.Data = mater;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "pmCode";
                operList.Add(oper);
                #endregion

                #region 备料子表
                DbPGMaterialSub sub = new DbPGMaterialSub();
                sub = new DbPGMaterialSub();
                sub.pmCode = pmCode;
                sub.isdel = 1;
                sub.delUser = userLogin.UserInfo().userCode; ;
                sub.delDate = getNow(); ;
                oper = new OperateModel();
                oper.Data = sub;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "pmCode";
                operList.Add(oper);
                #endregion

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                    //if (!string.IsNullOrEmpty(userCodes))
                    //    ding.sendDingMsg("BL", pKeys, userCodes, "派工单" + pKeys + "取消备货！", userLogin.UserInfo().userCode);
                }
                else
                {
                    rsl.Message = "没有数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 备料单退料
        /// </summary>
        /// <param name="pmCode"></param>
        /// <returns></returns>
        public ReturnResult BeiLiaoTuiLiao(string ids, string datas)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            StringBuilder sb = new StringBuilder();
            try
            {
                if (string.IsNullOrWhiteSpace(datas))
                {
                    rsl.Message = "没有要保存的数据";
                    return rsl;
                }
                DataTable dTable = JsonConvert.DeserializeObject<DataTable>(datas);
                foreach (DataRow dr in dTable.Rows)
                {
                    if (Convert.ToDecimal(dr["number"].ToString()) == 0)
                    {
                        rsl.Message = "请检查退料数量";
                        return rsl;
                    }
                }
                string codeLength = Tools.ConfigReader.Reader["CodeLength"];
                string blCode = CreateCodeInfo("TL", "退料单号", int.Parse(codeLength));
                string bltime = getNow();
                var jsons = JsonConvert.DeserializeObject<List<JObject>>(datas);
                #region 生成调拨单
                #region 获取转入仓库（去重后的）
                List<string> warelist = new List<string>();
                DataTable table = new DataTable();
                foreach (var obj in jsons)
                {
                    if (!warelist.Contains(obj["wareCode"].ToString()))
                        warelist.Add(obj["wareCode"].ToString());
                }
                #endregion
                #region 获取转出仓库（客户参数）
                sb.Clear();
                sb.Append(" select parValue from sys_parameters_info where parCode='dbzrck' ");
                var parTable = cmd.GetDataTable(sb.ToString());
                var outware = "";
                if (parTable.Rows.Count > 0)
                    outware = parTable.Rows[0][0].ToString();
                else
                    outware = "bcp";
                #endregion
                U8_13 u8 = new U8_13();
                DataTable cloTable = dTable.Clone();
                #region 对数据进行分组。
                foreach (DataRow dr in dTable.Rows)
                {
                    if (cloTable.Rows.Count > 0)
                    {
                        var rows = cloTable.Select("proCode='" + dr["proCode"].ToString() + "' and wareCode='" +
                            dr["wareCode"].ToString() + "' and yanse='" + dr["yanse"].ToString() + "'" +
                            " and shangbiao='" + dr["shangbiao"].ToString() + "'");
                        if (rows.Length > 0)
                        {
                            rows[0]["number"] = (Convert.ToDecimal(rows[0]["number"]) +
                                Convert.ToDecimal(dr["number"])).ToString();
                        }
                        else
                        {
                            cloTable.ImportRow(dr);
                        }
                    }
                    else
                    {
                        //DataRow newrow = dr;
                        cloTable.ImportRow(dr);
                    }
                }
                #endregion
                #region 获取发生类别
                var inType = "221"; var outType = "122";
                var typeTable = getBLType();
                if (typeTable.Rows.Count > 0)
                {
                    foreach (DataRow dr in typeTable.Rows)
                    {
                        if (dr["parCode"].Equals("bl_InType"))
                            inType = dr["parValue"].ToString();
                        else if (dr["parCode"].Equals("bl_OutType"))
                            outType = dr["parValue"].ToString();
                    }
                }
                #endregion
                //rsl = u8.MaterialOut(cloTable);
                rsl = u8.TransVouchDirectTL(cloTable, warelist, outware, inType, outType);
                #region   提示信息,新增退料记录
                if (rsl.Result)
                {
                    var relationBar = rsl.Data;
                    #region 备料主表
                    DbPGMaterialMain mater;
                    mater = new DbPGMaterialMain();
                    mater.pmCode = blCode;
                    mater.plCode = ids;
                    //mater.rowNo = rowNo;
                    mater.status = "bl-nin";
                    mater.isdel = 0;
                    mater.createtime = bltime;
                    mater.createuser = userLogin.UserInfo().userCode;
                    oper = new OperateModel();
                    oper.Data = mater;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);
                    #endregion

                    #region 备料子表
                    DbPGMaterialSub sub = new DbPGMaterialSub();

                    foreach (var obj in jsons)
                    {
                        if (obj.Property("number") == null)
                        {
                            continue;
                        }
                        if (string.IsNullOrWhiteSpace(obj["wareCode"].ToString()))
                        {
                            rsl.Message = "请录入目标仓库";
                            return rsl;
                        }
                        if (obj["positionCode"] != null && string.IsNullOrWhiteSpace(obj["positionCode"].ToString()))
                        {
                            sb.Clear();
                            sb.Append("select count(*) from fun_CommonData_Info where cType='WP' ");
                            sb.Append("and status='Y' and isDel=0 and specFile='" + userLogin.UserInfo().baseCode);
                            sb.Append("' and parentCode='" + obj["wareCode"].ToString() + "'");
                            var psTable = cmd.GetDataTable(sb.ToString());//查仓库是否有货位
                            var a = psTable.Rows[0][0].ToString();
                            if (Convert.ToDecimal(psTable.Rows[0][0].ToString()) > 0)
                            {
                                rsl.Message = "该仓库存在货位，请选择目标货位";
                                return rsl;
                            }
                        }
                        sub = new DbPGMaterialSub();
                        sub.pmCode = blCode;
                        sub.wareCode = obj["wareCode"].ToString();
                        sub.proCode = obj["proCode"].ToString();
                        if (obj["positionCode"] != null)
                            sub.positionCode = obj["positionCode"].ToString();
                        sub.number = obj["number"].ToString();
                        sub.isdel = 0;
                        sub.status = "bl-nin";
                        oper = new OperateModel();
                        oper.Data = sub;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                    }
                    #endregion

                    if (operList.Count > 0)
                    {
                        if (operList.Count == 1)//只添加了主表信息，子表全continue了
                        {
                            rsl.Message = "未正确填入退料数量，退料失败！";
                            return rsl;
                        }
                        rsl = cmd.MoreUpdate(operList);
                        if (rsl.Result)
                        {
                            sb.Clear();
                            sb.Append("update pi_PaiGong_material_main set relationBar='" + relationBar + "' where pmCode ='" + blCode + "'");
                            rsl = cmd.UpdateSql(sb.ToString());

                            if (rsl.Result)
                            {
                                #region  修改状态
                                operList = new List<OperateModel>();
                                #region 备料主表
                                DbPGMaterialMain m;
                                m = new DbPGMaterialMain();
                                m.pmCode = blCode;
                                m.status = "bl-in";
                                oper = new OperateModel();
                                oper.Data = m;
                                oper.Types = OperateModel.OperateType.Edit;
                                oper.Conditions = "pmCode";
                                operList.Add(oper);
                                #endregion

                                #region 备料子表
                                DbPGMaterialSub s = new DbPGMaterialSub();
                                s = new DbPGMaterialSub();
                                s.pmCode = blCode;
                                s.status = "bl-in";
                                oper = new OperateModel();
                                oper.Data = s;
                                oper.Types = OperateModel.OperateType.Edit;
                                oper.Conditions = "pmCode";
                                operList.Add(oper);
                                #endregion
                                if (operList.Count > 0)
                                {
                                    rsl = cmd.MoreUpdate(operList);
                                }
                                else
                                {
                                    rsl.Message = "修改调拨单状态错误，没有数据！";
                                    return rsl;
                                }
                                #endregion
                            }
                            else
                            {
                                rsl.Message = "回写退料调拨单号错误！";
                                return rsl;
                            }
                        }
                        else
                        {
                            rsl.Message = "生成退料记录失败！";
                            return rsl;
                        }
                    }

                }
                else
                {
                    return rsl;
                }
                #endregion
                #endregion

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 计划待派工数
        /// </summary>
        public ReturnResult getNeedPg()
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.Append("select count(*) count from V_ProductionPlan_process where status = 'ps-dsc' ");
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 派工单未完成数
        /// </summary>
        public ReturnResult getPgNFinish()
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select count(*) count from V_PlanPaiChan_info ");
                sb.Append(" where isDel=0 and isFinish=0  ");
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 报工合格数  不合格数
        /// </summary>
        public ReturnResult getBgNum()
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select isnull (Sum(convert(decimal(18,1),yNum)),0) yNum,isnull (Sum(convert(decimal(18,1),nNum)),0) nNum  ");
                sb.Append("from V_Plan_BaoGong_Main m inner join V_PlanPaiChan_info p on p.pKey=m. pKey ");
                sb.Append("and p.isFinish=0 where m.isDel=0 and p.isDel=0");
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取需要创建包装计划的生产计划
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult ToBaoZhuangTask(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0 ");
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "status")
                            {
                                var arr = obj.Value.ToString().Split(',');
                                string status = "";
                                foreach (string s in arr)
                                {
                                    if (!string.IsNullOrWhiteSpace(s))
                                    {
                                        status += "'" + s + "',";
                                    }
                                }
                                sb.Append("status in (" + status.TrimEnd(',') + ")");
                            }
                            else if (obj.Name == "isPrint")
                            {
                                if (obj.Value.ToString().Equals("0"))
                                {
                                    sb.Append(" isPrint is null ");
                                }
                                else
                                {
                                    sb.Append(" isPrint ='" + obj.Value.ToString() + "' ");
                                }
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }

                        }
                    }
                }

                var list = cmd.PageList("V_PackPlan_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                TotalCount(ref list);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        private void TotalCount(ref List<Dictionary<string, string>> list)
        {
            try
            {
                StringBuilder sb;
                for (int i = 0; i < list.Count; i++)
                {
                    sb = new StringBuilder();
                    sb.Append("select isnull(SUM(CONVERT(decimal(18,2),number)),'0') num from V_PlanPaiChan_info ");
                    sb.Append(" where isdel=0 and ppid='" + list[i]["id"].ToString() + "' and gxCode in(select cgxCode from");
                    sb.Append(" fun_GxPrice_info where isdel=0 and gxCode in(select cCode from fun_CommonData_Info where specFile='sysRelation'))");

                    var table = cmd.GetDataTable(sb.ToString());
                    string num = "0";
                    if (table.Rows.Count > 0 && !string.IsNullOrEmpty(table.Rows[0]["num"].ToString()))
                    {
                        num = table.Rows[0]["num"].ToString();
                    }
                    list[i]["doNum"] = num;//已完成数

                    sb.Clear();
                    sb.Append("select * from V_PlanPaiChan_info where isdel=0 and ppId='" + list[i]["id"].ToString() + "' ");
                    var pgtable = cmd.GetDataTable(sb.ToString());
                    if (pgtable.Rows.Count > 0)
                        list[i]["isPaiGong"] = "1";
                    else
                        list[i]["isPaiGong"] = "0";
                }
            }
            catch (Exception ex)
            {
                txt.AddLogMsg("获取已下计划数报错(TotalCount):" + ex.Message);
            }
        }
        /// <summary>
        /// 计划配置生产工艺
        /// </summary>
        /// <param name="p_pIds">计划子表id</param>
        /// <param name="gyCode">工艺编码</param>
        /// <returns></returns>
        public ReturnResult SetPlanGongYi(string p_pIds, string gyCode, string type = null)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                operList = new List<OperateModel>();
                if (string.IsNullOrWhiteSpace(p_pIds) || string.IsNullOrWhiteSpace(gyCode))
                {
                    rsl.Message = "关键参数丢失,请联系开发人员";
                    return rsl;
                }

                DbProductionPlanPro pp;
                DbPlanGongXu p_gy;
                //sb.Append("update pi_ProductionPlan_products set cu_gy='"+ gyCode +"',");
                //sb.Append("status='ps-pg-set' where id in("+ p_pIds +")");

                #region   工艺信息表
                sb.Clear();
                if (string.IsNullOrEmpty(type))
                {
                    sb.Append("select gy.* ,gx.gxCode parentCode,c.orderNum from fun_products_gx gy ");
                    sb.Append("inner join fun_GxPrice_info gx on gx.cgxCode = gy.gxCode and gx.isdel=0 ");
                    sb.Append("inner join fun_CommonData_Info c on gx.gxCode=c.cCode and c.cType='Gx' ");
                    sb.Append("where gyCode = '" + gyCode + "' ");
                    sb.Append("order by c.orderNum ");
                }
                else
                {
                    sb.Append("select cgxCode gxCode,gxCode parentCode from fun_GxPrice_info where isdel=0 and cgxCode='" + gyCode + "'");
                }
                var gyTable = cmd.GetDataTable(sb.ToString());//工艺信息
                #endregion

                var p_pId = p_pIds.Split(',');
                foreach (var s in p_pId)
                {
                    #region 修改products表 工艺 字段
                    pp = new DbProductionPlanPro();
                    pp.id = Convert.ToInt32(s);
                    pp.cu_gy = gyCode;
                    pp.status = "ps-pg-set";
                    oper = new OperateModel();
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    oper.Data = pp;
                    operList.Add(oper);
                    #endregion

                    # region 计划存货信息
                    sb.Clear();
                    sb.Append("select * from pi_ProductionPlan_products where id=" + s);
                    var pTable = cmd.GetDataTable(sb.ToString());//计划存货信息
                    #endregion

                    # region 计划工序信息  已有的话删除已有工序
                    sb.Clear();
                    sb.Append("select * from pi_ProductionPlan_process where plCode='" + pTable.Rows[0]["plCode"].ToString());
                    sb.Append("' and rowNo='" + pTable.Rows[0]["rowNO"].ToString() + "'");
                    sb.Append(" and orderCode='" + pTable.Rows[0]["orderCode"].ToString() + "'");
                    var pcTable = cmd.GetDataTable(sb.ToString());//计划工序信息
                    if (pcTable.Rows.Count > 0)
                    {
                        //删除已有工序
                        p_gy = new DbPlanGongXu();
                        p_gy.plCode = pTable.Rows[0]["plCode"].ToString();
                        p_gy.rowNo = pTable.Rows[0]["rowNO"].ToString();
                        p_gy.orderCode = pTable.Rows[0]["orderCode"].ToString();
                        oper = new OperateModel();
                        oper.Types = OperateModel.OperateType.Delete;
                        oper.Conditions = "plCode,rowNo,orderCode";
                        oper.Data = p_gy;
                        operList.Add(oper);
                    }
                    #endregion

                    #region 在process表内插入数据
                    var fstGX = gyTable.Rows[0]["parentCode"].ToString();//第一道工序
                    foreach (DataRow dr in gyTable.Rows)
                    {
                        p_gy = new DbPlanGongXu();
                        p_gy.plCode = pTable.Rows[0]["plCode"].ToString();
                        p_gy.proCode = pTable.Rows[0]["proCode"].ToString();
                        p_gy.orderCode = pTable.Rows[0]["orderCode"].ToString();
                        p_gy.rowNo = pTable.Rows[0]["rowNO"].ToString();
                        p_gy.gxCode = dr["gxCode"].ToString();
                        p_gy.createuser = userLogin.UserInfo().userCode;
                        p_gy.createtime = getNow();
                        p_gy.isChild = 1;
                        p_gy.parentCode = dr["parentCode"].ToString();
                        p_gy.status = "ps-dsc";
                        p_gy.gyCode = gyCode;
                        p_gy.ppId = s;
                        if (gyTable.Rows.Count == 1)//包装计划（只包含一道工序）
                        {
                            p_gy.canBg = 1;
                        }
                        else
                        {
                            if (dr["parentCode"].ToString().Equals(fstGX))

                                p_gy.canBg = 1;
                            else
                                p_gy.canBg = 0;
                        }
                        oper = new OperateModel();
                        oper.Types = OperateModel.OperateType.Add;
                        oper.Data = p_gy;
                        operList.Add(oper);
                    }
                    #endregion
                }
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
                //rsl = cmd.UpdateSql(sb.ToString());
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public ReturnResult GetPrintPDFNew(string ids)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_ProductionPlan_products where id in(" + ids + ")");
                var table = cmd.GetDataTable(sb.ToString());

                if (table.Rows.Count > 0)
                {
                    CuDbHelper cuDb = new CuDbHelper();
                    var wb = new GL_WorkBook();
                    int sRow = 1, eRow = 5, j = 0;
                    foreach (DataRow r in table.Rows)
                    {
                        string plCode = r["plCode"].ToString();
                        string sql = "select * from pi_ProductionPlan_info where plCode='" + plCode + "' and isdel=0";
                        var pTable = cmd.GetDataTable(sql);

                        j++;
                    }
                    string newName = getTimeString();
                    rsl = new FrontReader().UploadModel_UsingTemplate(newName + ".xlsx", wb, "计划单模板.xlsx");
                    var fileName = rsl.Data.ToString();
                    fileName = fileName.Replace(".xlsx", ".pdf");
                    rsl.Data = fileName;
                }



                // 按照模型渲染表格


            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public MemoryStream toExcel(string ids)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_ProductionPlan_products where id in(" + ids + ")");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    CuDbHelper cuDb = new CuDbHelper();
                    var wb = new GL_WorkBook();
                    int rCount = 0;
                    MemoryStream ms = null;
                    NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
                    //添加一个sheet
                    NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
                    IDataFormat dataformat = book.CreateDataFormat();
                    ICell cell;
                    short rowHeight = 500;
                    var t_Style = ExcelBodyStyle(book, false, true);//单元格样式
                    var c_Style = ExcelBodyStyle(book, false, false);//单元格样式
                    sheet1.SetColumnWidth(1, 14 * 256);//宽度设置
                    CellRangeAddress region;
                    foreach (DataRow r in table.Rows)
                    {
                        string prlCode = r["prlCode"].ToString();//拼出来的计划号（区分子计划）
                        string plCode = r["plCode"].ToString();
                        #region 构建打印表格

                        NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(rCount);
                        region = new CellRangeAddress(rCount, rCount + 4, 7, 10);//合并单元格
                        sheet1.AddMergedRegion(region);

                        #region 创建二维码 prlCode
                        for (int i = 7; i <= 10; i++)
                        {
                            sheet1.SetColumnWidth(i, 6 * 256);//宽度设置
                        }
                        QRCodeGenerator qrGenerator = new QRCodeGenerator();
                        QRCodeData qrCodeData = qrGenerator.CreateQrCode(prlCode, QRCodeGenerator.ECCLevel.Q);
                        QRCode qrCode = new QRCode(qrCodeData);
                        Bitmap qrCodeImage = qrCode.GetGraphic(20);


                        var memoryStream = new MemoryStream();
                        qrCodeImage.Save(memoryStream, ImageFormat.Png);
                        var barCodeIndex = book.AddPicture(memoryStream.ToArray(), PictureType.PNG);
                        IDrawing drawing = sheet1.CreateDrawingPatriarch();

                        //第四步：设置锚点 （在起始单元格的X坐标0-1023，Y的坐标0-255，
                        //在终止单元格的X坐标0-1023，Y的坐标0-255，
                        //起始单元格行数，列数，终止单元格行数，列数）
                        //IClientAnchor anchor = drawing.CreateAnchor(0, 0, 0, 0, rCount, 7, rCount + 4, 10);
                        IClientAnchor anchor = drawing.CreateAnchor(0, 0, 0, 0, 7, rCount, 10, rCount + 4);

                        IPicture picture = drawing.CreatePicture(anchor, barCodeIndex);
                        #endregion

                        #region 客户名称
                        //NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(rCount);
                        cell = row1.CreateCell(1);
                        cell.SetCellValue("客户名称");
                        cell.CellStyle = t_Style;

                        cell = row1.CreateCell(2);
                        cell.SetCellValue(r["cuName"].ToString());
                        row1.Height = rowHeight;
                        cell.CellStyle = c_Style;
                        region = new CellRangeAddress(rCount, rCount, 2, 6);//合并单元格
                        sheet1.AddMergedRegion(region);
                        rCount++;
                        #endregion

                        #region 生产单号  prlCode
                        row1 = sheet1.CreateRow(rCount);
                        cell = row1.CreateCell(1);
                        cell.SetCellValue("生产单号");
                        cell.CellStyle = t_Style;
                        cell = row1.CreateCell(2);
                        cell.SetCellValue(prlCode);
                        cell.CellStyle = c_Style;
                        row1.Height = rowHeight;
                        region = new CellRangeAddress(rCount, rCount, 2, 6);//合并单元格
                        sheet1.AddMergedRegion(region);
                        rCount++;
                        #endregion

                        #region 货号
                        row1 = sheet1.CreateRow(rCount);
                        cell = row1.CreateCell(1);
                        cell.SetCellValue("货号");
                        cell.CellStyle = t_Style;
                        cell = row1.CreateCell(2);
                        cell.SetCellValue(r["proCode"].ToString());
                        cell.CellStyle = c_Style;
                        row1.Height = rowHeight;
                        region = new CellRangeAddress(rCount, rCount, 2, 6);//合并单元格
                        sheet1.AddMergedRegion(region);
                        rCount++;
                        #endregion

                        #region 存货名称
                        row1 = sheet1.CreateRow(rCount);
                        cell = row1.CreateCell(1);
                        cell.SetCellValue("名称");
                        cell.CellStyle = t_Style;
                        cell = row1.CreateCell(2);
                        cell.SetCellValue(r["proName"].ToString());
                        cell.CellStyle = c_Style;
                        row1.Height = rowHeight;
                        region = new CellRangeAddress(rCount, rCount, 2, 6);//合并单元格
                        sheet1.AddMergedRegion(region);
                        rCount++;
                        #endregion

                        #region 规格
                        var sql = "select * from fun_Inventory_Info where proCode = '" + r["proCode"].ToString() + "'";
                        var proTable = cmd.GetDataTable(sql);
                        if (proTable.Rows.Count > 0)
                        {
                            row1 = sheet1.CreateRow(rCount);
                            cell = row1.CreateCell(1);
                            cell.SetCellValue("规格");
                            cell.CellStyle = t_Style;
                            cell = row1.CreateCell(2);
                            cell.SetCellValue(proTable.Rows[0]["spec"].ToString());
                            cell.CellStyle = c_Style;
                            //cell = row1.CreateCell(3);
                            //cell.SetCellValue("重量");
                            //cell.CellStyle = t_Style;
                            //cell = row1.CreateCell(4);
                            //cell.SetCellValue(proTable.Rows[0]["cu_kezhong"].ToString());
                            //cell.CellStyle = c_Style;
                        }
                        //cell = row1.CreateCell(5);
                        //cell.SetCellValue("颜色");
                        //cell.CellStyle = t_Style;
                        //cell = row1.CreateCell(6);
                        //cell.SetCellValue(r["cu_yanse"].ToString());
                        //cell.CellStyle = c_Style;
                        row1.Height = rowHeight;
                        rCount++;
                        #endregion

                        #region 重量/颜色
                        if (proTable.Rows.Count > 0)
                        {
                            row1 = sheet1.CreateRow(rCount);
                            cell = row1.CreateCell(1);
                            cell.SetCellValue("重量");
                            cell.CellStyle = t_Style;
                            cell = row1.CreateCell(2);
                            cell.SetCellValue(proTable.Rows[0]["cu_kezhong"].ToString());
                            cell.CellStyle = c_Style;
                        }
                        cell = row1.CreateCell(3);
                        cell.SetCellValue("颜色");
                        cell.CellStyle = t_Style;
                        cell = row1.CreateCell(4);
                        cell.SetCellValue(r["cu_yanse"].ToString());
                        cell.CellStyle = c_Style;
                        row1.Height = rowHeight;
                        rCount++;
                        #endregion

                        #region 商标/吊牌
                        row1 = sheet1.CreateRow(rCount);
                        cell = row1.CreateCell(1);
                        cell.SetCellValue("商标");
                        cell.CellStyle = t_Style;
                        cell = row1.CreateCell(2);
                        cell.SetCellValue(r["cu_shangbiao"].ToString());
                        cell.CellStyle = c_Style;
                        cell = row1.CreateCell(3);
                        cell.SetCellValue("吊牌");
                        cell.CellStyle = t_Style;
                        cell = row1.CreateCell(4);
                        cell.SetCellValue(r["cu_diaopai"].ToString());
                        cell.CellStyle = c_Style;
                        row1.Height = rowHeight;
                        rCount++;
                        #endregion

                        #region 数量/箱规
                        row1 = sheet1.CreateRow(rCount);
                        cell = row1.CreateCell(1);
                        cell.SetCellValue("数量");
                        cell.CellStyle = t_Style;
                        cell = row1.CreateCell(2);
                        cell.SetCellValue(r["number"].ToString());
                        cell.CellStyle = c_Style;
                        cell = row1.CreateCell(3);
                        cell.SetCellValue("箱规");
                        cell.CellStyle = t_Style;
                        cell = row1.CreateCell(4);
                        cell.SetCellValue(r["cu_zhuangxiangyq"].ToString());
                        cell.CellStyle = c_Style;
                        row1.Height = rowHeight;
                        rCount++;
                        #endregion

                        #region 内包装
                        row1 = sheet1.CreateRow(rCount);
                        cell = row1.CreateCell(1);
                        cell.SetCellValue("内包装");
                        cell.CellStyle = t_Style;
                        cell = row1.CreateCell(2);
                        cell.SetCellValue(r["cu_neibaozhuangyq"].ToString());
                        cell.CellStyle = c_Style;
                        row1.Height = rowHeight;
                        region = new CellRangeAddress(rCount, rCount, 2, 6);//合并单元格
                        sheet1.AddMergedRegion(region);
                        rCount++;
                        #endregion

                        #region 发货来源
                        var u8Order = r["orderCode"].ToString();
                        var rowNo = r["rowNo"].ToString();
                        var u8SoDetailsSql = " select cDefine24 from SO_SODetails where cSOCode = '" + u8Order + "' and iRowNo = " + rowNo;
                        var u8SoDetailsDt = cuDb.getData(u8SoDetailsSql, userLogin.UserInfo().baseCode);
                        string memo = "";
                        if (u8SoDetailsDt.Rows.Count > 0)
                        {
                            //memo = u8SoDetailsDt.Rows[0]["cMemo"].ToString();
                            memo = u8SoDetailsDt.Rows[0]["cDefine24"].ToString();
                        }
                        row1 = sheet1.CreateRow(rCount);
                        cell = row1.CreateCell(1);
                        cell.SetCellValue("发货来源");
                        cell.CellStyle = t_Style;
                        cell = row1.CreateCell(2);
                        cell.CellStyle = c_Style;
                        cell.SetCellValue(memo);
                        row1.Height = rowHeight;
                        region = new CellRangeAddress(rCount, rCount, 2, 6);//合并单元格
                        sheet1.AddMergedRegion(region);
                        rCount++;
                        #endregion

                        #region 备注 plCode
                        //var planMemoSql = "select memo from pi_ProductionPlan_products where plCode = '" + plCode + "' and isdel=0 ";
                        var planMemoSql = "select memo from pi_ProductionPlan_products where prlCode = '" + prlCode + "' and isdel=0 ";
                        var planMemoDt = cmd.GetDataTable(planMemoSql);
                        var memos = "";
                        foreach (DataRow dr in planMemoDt.Rows)
                        {
                            memos = memos + dr["memo"].ToString() + ",";
                        }
                        row1 = sheet1.CreateRow(rCount);
                        cell = row1.CreateCell(1);
                        cell.SetCellValue("备  注");
                        cell.CellStyle = t_Style;
                        cell = row1.CreateCell(2);
                        cell.SetCellValue(memos.TrimEnd(','));
                        cell.CellStyle = c_Style;
                        row1.Height = rowHeight;
                        region = new CellRangeAddress(rCount, rCount, 2, 6);//合并单元格
                        sheet1.AddMergedRegion(region);
                        rCount++;
                        #endregion

                        #region 生产工艺名称
                        sb.Clear();
                        sb.Append("select gxCode,gxName,gx.orderNum from  V_ProductionPlan_process pro ");
                        sb.Append("left join fun_CommonData_Info gx on pro.parentCode= gx.cCode ");
                        sb.Append(" where pro.ppId = " + r["id"].ToString() + " order by ordernum");
                        var gxDt = cmd.GetDataTable(sb.ToString());
                        string gxNames = "";
                        foreach (DataRow gxRow in gxDt.Rows)
                        {
                            gxNames = gxNames + gxRow["gxName"].ToString() + "-";
                        }
                        row1 = sheet1.CreateRow(rCount);
                        cell = row1.CreateCell(1);
                        cell.SetCellValue(gxNames.TrimEnd('-'));
                        cell.CellStyle = c_Style;
                        row1.Height = rowHeight;
                        region = new CellRangeAddress(rCount, rCount, 1, 10);//合并单元格
                        sheet1.AddMergedRegion(region);
                        rCount++; rCount++;
                        #endregion

                        #endregion

                    }

                    var usql = "update pi_ProductionPlan_products set isPrint =1 where id in (" + ids + ")";
                    cmd.UpdateSql(usql);

                    ms = new System.IO.MemoryStream();
                    book.Write(ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    return ms;
                }
            }
            catch (Exception ex)
            {

            }
            return null;
        }

        /// <summary>
        /// 次品调拨自动任务
        /// </summary>
        /// <param name="isAuto">是否是自动任务</param>
        /// <returns></returns>
        public ReturnResult SyncProTransfer(bool isAuto = false, string date = null)
        {
            rsl = new ReturnResult();
            try
            {
                rsl = this.DefProTransfer(date);

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 次品调拨
        /// </summary>
        /// <param name="baseCode"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        private ReturnResult DefProTransfer(string date = null)
        {
            rsl = new ReturnResult();
            SysFrameWork.SystemBLL sysBLL = new SysFrameWork.SystemBLL();
            try
            {
                var happen = "bcp";
                var target = "008";
                #region 获取次品调拨的发生仓库和目标仓库
                rsl = sysBLL.getParameterByCode("cpdb");
                if (rsl.Result)
                {
                    var parslist = (List<Dictionary<string, string>>)rsl.Data;
                    if (parslist.Count > 0)
                    {
                        string par = parslist[0]["parValue"];
                        if (!string.IsNullOrWhiteSpace(par))
                        {
                            var obj = JsonConvert.DeserializeObject<JObject>(par);
                            happen = obj["happen"].ToString();
                            target = obj["target"].ToString();
                        }
                    }
                }
                #endregion

                //var date = getNowDate(-1);
                if (string.IsNullOrEmpty(date))
                    date = getNowDate(-1);
                StringBuilder sb = new StringBuilder();
                sb.Append("select '" + happen + "' wareCode,'' positionCode ,proCode,proName,SUM(CONVERT(decimal(18, 0), m.nNum)) number,");
                sb.Append("pp.cu_yanse color, pp.cu_shangbiao shangbiao from pi_PlanBaogong_main m ");
                sb.Append("inner join pi_PlanPaiGong_info p on p.tpCode = m.pKey and p.isDel = 0 ");
                sb.Append("inner join V_ProductionPlan_products pp on pp.id = p.ppId and pp.isdel = 0 ");
                sb.Append("where m.isDel = 0 and happenDate = '" + date + "' ");
                sb.Append("group by proCode,proName,pp.cu_yanse,pp.cu_shangbiao ");
                sb.Append("having SUM(CONVERT(decimal(18, 0), m.nNum)) > 0 ");

                var table = cmd.GetDataTable(sb.ToString());

                List<string> warelist = new List<string>();
                if (table.Rows.Count > 0)
                {
                    warelist.Add(happen);//调出仓库
                    #region 获取发生类别
                    var inType = "122"; var outType = "221";
                    var typeTable = getBLType();
                    if (typeTable.Rows.Count > 0)
                    {
                        foreach (DataRow dr in typeTable.Rows)
                        {
                            if (dr["parCode"].Equals("bl_InType"))
                                inType = dr["parValue"].ToString();
                            else if (dr["parCode"].Equals("bl_OutType"))
                                outType = dr["parValue"].ToString();
                        }
                    }
                    #endregion

                    U8_13 u8 = new U8_13();
                    rsl = new ReturnResult();
                    //rsl = u8.MaterialOut(cloTable);
                    rsl = u8.TransVouchDirect(table, warelist, target, inType, outType, "auto");

                }
                else
                {
                    rsl.Message = "调拨完成(无不合格品)";
                    rsl.Result = true;
                }

                #region  写入任务记录表sys_TaskCenter_info
                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                var tms = Convert.ToInt64(ts.TotalSeconds).ToString();
                sb.Clear();
                sb.Append("insert into sys_TaskCenter_info(id,businessType, businessId, contents, createtime, isFinish, memo)");
                sb.Append("values('" + tms + "','auto_DefProTransfer','" + date + "','次品生成调拨单',");
                sb.Append("'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + Convert.ToInt32(rsl.Result) + "','" + rsl.Message + "')");
                var r = cmd.UpdateSql(sb.ToString());

                #endregion

                txt.AddLogMsg(string.Format("次品调拨方法({0})，更新结果：{1}", "auto_DefProTransfer", JsonConvert.SerializeObject(rsl)));

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        //生成销售发票
        public ReturnResult saveFP(string data, string keyCode,string stocks)
        {
            rsl = new ReturnResult();
            try
            {
                #region 获取需要的数据
                string key = userLogin.UserInfo().userCode + keyCode;
                var c_data = Tools.Cache.GetCache(key);
                var table = JsonConvert.DeserializeObject<DataTable>(c_data.ToString());//销售订单的数据

                table.Columns.Add("use");
                table.Columns.Add("cwhCode");
                table.Columns.Add("cPosition");

                //var json = JsonConvert.DeserializeObject<JObject>(data);
                //table.Columns.Add("use");
                //table.Rows[0]["use"] = json["strock"];//发货数量
                //table.Columns.Add("cwhCode");

                var sTable = JsonConvert.DeserializeObject<DataTable>(stocks);//仓库现存量以及发货数量

                var newTable = table.Clone();//存发货信息

                if (sTable.Rows.Count > table.Rows.Count)
                {
                    DataRow dr = table.Rows[0];
                    table.ImportRow(dr);
                    for (int i = 0; i < sTable.Rows.Count - table.Rows.Count; i++)
                    {
                        sTable.ImportRow(dr);
                    }
                }
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    table.Rows[i]["cwhCode"] = sTable.Rows[i]["cWhCode"];
                    table.Rows[i]["cPosition"] = sTable.Rows[i]["cPosCode"];
                    table.Rows[i]["use"] = sTable.Rows[i]["fhNum"];
                }
               
                //StringBuilder sb = new StringBuilder();
                //sb.Append("select parValue from sys_parameters_info where parCode = 'saleOutWareHouse'");
                //var whTable = cmd.GetDataTable(sb.ToString());
                //if (whTable.Rows.Count > 0)
                //{
                //    table.Rows[0]["cwhCode"] = whTable.Rows[0]["parValue"];//出库仓库编码
                //}
                //else
                //{
                //    table.Rows[0]["cwhCode"] = "011";
                //}
                #endregion

                U8_13 u8 = new U8_13();
                rsl = u8.SaleBillVouch(table);
                if (rsl.Result)
                {

                }
                else
                {
                    return rsl;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


    }
}
